简体   繁体   中英

Angular.js: How to count number of elements in nested ng-repeat

So, the situation I have is I'm looping through a list of JSON objects, which contain a list as an attribute. I have an inner loop repeating on that list attribute. Something along the lines of this:

Number of results: {{count}}

<div ng-repeat="jsonObject in outerList | someFilter" ng-show="innerList.length">
    <h1>{{jsonObject.Name}}</h1><br>
    <div ng-repeat="items in jsonObject.listAttr | someOtherFilter as innerList">
        {{items.data}}<br>
    </div>
    <br>
</div>

The issue I'm facing is finding a way to grab an aggregated count of all the elements across every iteration of the inner repeat. So, if the first jsonObject has 2 things that match the inner filter, and the second jsonObject has 3 things that match the inner filter, we show a count of 5 outside the whole loop (in the count variable above, or something similar).

I've looked into a number of ways to try and get that count, but without any success. One of the wrenches that is thrown into some solutions I've found is that the filters are something that the user can change on the fly (via a search box, for one), so I can't just apply all the filters in the controller at page load and display that. I may start with 5 objects, until the user types something into the search box that drops the number down to 2.

I think that you want this...

Function in the $scope

$scope.moreOne = function(counter) {
  $scope[counter]++;
}

Each element in jsonObject, this is counted

<div ng-repeat="jsonObject in outerList | someFilter" ng-show="innerList.length">
      <h1>{{jsonObject.Name}}</h1><br>
      <div ng-repeat="items in jsonObject.listAttr | someOtherFilter as innerList" ng-init="moreOne('count')">
          {{items.data}}<br>
      </div>
      <br>
  </div>

Do you see the ng-init?

ng-init="moreOne('count')"

Maybe this solution isn't the best... Saludos! :-)

UPDATE

Ok, you can use watchers to controller the changes of model. If outerList or any (you can define a watcher for any property) changes, the watcher will be triggered. And you only need this code without moreOne function :-)

    $scope.$watch("outerList", function(list) {
      $scope.count = 0;
      for(var i = 0; i < list.length; i++) {
        $scope.count += list[i]['listAttr'].length;
      }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM