首页 > 解决方案 > 如何使用angularjs webapi中的ng-change将文本框聚焦在表格中?

问题描述

当我更改数量时,数量焦点会丢失.. 点击此处查看图片

AngularJS 代码:ng-change 代码

$scope.txtqty = function (item) {
    var id = item.Id;
    $http.put("/api/Products/txtqty/" + id, item).then(function (response) {
        $scope.gridproducts = response.data;
    })
}

HTML表格代码

    <table>
    <tbody>
        <tr ng-repeat="item in gridproducts">
            <td ng-click="griddelete(item.Id)"><a class="delete"><i class="fa fa-times-circle-o"></i></a></td>
            <td class="name">{{item.ProductName}}</td>
            <td>{{item.ProductRate}}</td>
            <td><input class="form-control qty" type="text" style="width:50px" ng-change="txtqty(item)" ng-model="item.ProductQty" value="{{item.ProductQty}}"></td>
            <td>{{item.TotalAmount}}</td>
        </tr>
        <tr></tr>
    <tfoot>
        <tr>
            <th colspan="2"></th>
            <th colspan="2"><b>Total</b></th>
            <th><b>{{gridproducts[0].TotalBill}}</b></th>
            </tr><tr>
            <th colspan="2"><b></b></th>
            <th colspan="2"><b>Total Items</b></th>
            <th><b>25</b></th>
            </tr>
        </tfoot>
</table>

Webapi 控制器代码这是 webapi 控制器在这里你可以看到

 [System.Web.Http.Route("api/Products/txtqty/{id}")]
        [ResponseType(typeof(void))]
        public IHttpActionResult PuttxtQTY(int id, Product Pro)
        {
            var q = gridlist.Where(x => x.Id == id).FirstOrDefault();
            if (q != null)
            {
                q.ProductQty = Pro.ProductQty;
                q.TotalAmount = q.ProductQty * q.ProductRate;
                q.TotalBill = gridlist.Sum(x => x.TotalAmount);
                foreach (var item in gridlist)
                {
                    item.TotalBill = q.TotalBill;
                }
            }
            return Ok(gridlist);
        }

标签: angularjsasp.net-mvcasp.net-web-apiangularjs-directive

解决方案


您可以给每个输入一个唯一的 ID 并手动重新聚焦它:

输入时带有 ID 的 HTML

<td><input class="form-control qty" type="text" id="productQty_{{item.id}}" style="width:50px" ng-change="txtqty(item)" ng-model="item.ProductQty" value="{{item.ProductQty}}"></td>

通过重新聚焦逻辑调整的功能

$scope.txtqty = function (item) {
    var id = item.Id;
    $http.put("/api/Products/txtqty/" + id, item).then(function (response) {
        $scope.gridproducts = response.data;
        document.getElementById("productQty_" + id).focus();
    })
}

希望这能完成工作:)


推荐阅读