对 ng-repeat 中的行进行编号

Number the rows in ng-repeat

我有一个 table,里面有一个 ng-repeat 指令。它使用过滤器过滤掉不具有 属性 数量>0 的对象。我需要给一个序列号。到每一行。请注意,行不是固定的。如果用户将产品的数量更改为 0,则该产品将从 table 中删除。

<table class="table table-striped">
    <tr>
    <th>S.no</th><th>Product Name</th><th>Qty</th><th>Sub-Total</th>
  </tr>
  <tr class="orders" ng-repeat="product in products" ng-if="product.qty">
    <td>{{$index}}</td><td>{{product.name}}</td><td> <input type="number" min="0" ng-blur="product.qty = qty" ng-model="qty" value="{{product.qty}}"> </td> <td>{{product.qty*product.price | currency:"&#8377;"}}</td>
  </tr>
</table>

现在,此代码的问题在于,$index 给出了产品数组中产品的实际索引。我需要它在过滤后的数组中给出索引。我该怎么做?

ng-repeat 中使用过滤器:

HTML

<tr class="orders" ng-repeat="product in products | filter: hasQty">
    <td>{{$index}}</td><td>{{product.name}}</td><td> <input type="number" min="0" ng-blur="product.qty = qty" ng-model="qty" value="{{product.qty}}"> </td> <td>{{product.qty*product.price | currency:"&#8377;"}}</td>
</tr>

JS:

$scope.hasQty = function (value) {
    return value.qty > 0
}

未测试。

您可以按如下方式预先筛选项目:

<tr class="orders" ng-repeat="product in filterItems(products)">
    <td>{{$index}}</td><td>{{product.name}}</td><td> <input type="number" min="0" ng-blur="product.qty = qty" ng-model="qty" value="{{product.qty}}"> </td> <td>{{product.qty*product.price | currency:"&#8377;"}}</td>
</tr>

控制器:

$scope.filterItems = function(items) {
    var filtered_items = [];
    angular.forEach(items, function(item) {
        if(item.qty > 0) {
            filtered_items.push(item)
        }
    })
    return filtered_items;
}