Ad

How To Count Items In Nested Ng-repeat Without $index

I want to count iteration of ng-repeat, when condition match.

I've tried $index but it print for all itration/items in nested ng-repeat

Fiddle link :https://jsfiddle.net/gdr7p1zj/1/

<tbody ng-controller="MainCtrl">
    <tr ng-repeat-start="a in test1">
          <td>{{a.categoryName}}(count_here)</td>
        </tr>
        <tr ng-repeat-end ng-repeat="b in test" ng-if="a.categoryId==b.categoryId">
          <td>{{b.name}}</td>
        </tr>
</tbody>
i want like this 
category_one(4)  <=item count 4 items in this category so 4 will display
    item1
    item2
    item3
    item4 
category_two(2)
    item5
    item6
<!-- this is in controller -->

$scope.test1=[{
        categoryId:'1',categoryName:'category one'
    },
    {
        categoryId:'2',categoryName:'category two'
    }]
    $scope.test = [
        {categoryId:'1',name:'cate 1 elem0'},
        {categoryId:'1',name:'cate 1 elem1'},
        {categoryId:'2',name:'cate 2 elem'}
    ];
});      
Ad

Answer

An option is to create a function (getCount) in the controller which do the count, something like this:

$scope.getCount = function(categoryId) {        // returns the count by matching by categoryId
  return $scope.test.filter(function(element) { // first, filter elements in `test`
    return element.categoryId === categoryId;   // matching by categoryId
  }).length;                                    // then, return the count of how many results we got after the filter
}

And in the html call that function like this:

<tbody ng-controller="MainCtrl">
    <tr ng-repeat-start="a in test1">
      <td>{{a.categoryName }} ({{getCount(a.categoryId)}})</td> <!-- <-- call the function in order to display the count -->
    </tr>
    <tr ng-repeat-end ng-repeat="b in test" ng-if="a.categoryId == b.categoryId">
      <td>{{b.name}}</td>
    </tr>
</tbody>

See a demo here: https://jsfiddle.net/lealceldeiro/v9gj1ok4/11/

Ad
source: stackoverflow.com
Ad