Ayush Gupta
Ayush Gupta

Reputation: 1717

Number the rows in ng-repeat

I have a table which has a ng-repeat directive in it. It uses a filter to filter out objects not having property qty>0. I need to give a serial no. to each of the rows. Note that the rows are not fixed. If a user changes the qty of a product to make it 0, it is removed from the 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>

Now, the problem with this code is that, the $index gives the actual index of the product in the products array. I need it to give the index in the filtered array. How do I do that?

Upvotes: 1

Views: 5877

Answers (2)

Tarun Dugar
Tarun Dugar

Reputation: 8971

You can filter the items beforehand as follows:

<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>

Controller:

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

Upvotes: 3

michelem
michelem

Reputation: 14590

Use filter in 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
}

Untested.

Upvotes: 2

Related Questions