njfife
njfife

Reputation: 3575

Maintaining a count of the number of results being displayed with AngularJS ng-repeat

I made a Plunker to demo my question: http://plnkr.co/edit/sT9cFUFPhR2Z45SiRW7V?p=preview

It seems like it updates the count if the search is a new search but once everything has been cached it stops updating the count. There doesn't seem to be a way to clear the cache of ng-repeat (that I know of) and I am not sure if I really want to do that anyway since it would hurt performance.

Is there a way to keep an up to date count of the total rows being displayed in one or more ng-repeats?

HTML:

  <body ng-app="app">
    <div ng-controller="ctrl as c">
      <h1>{{'Count: ' + (c.count + c.count2)}}</h1>

      Search by name: <input type="text" ng-model="name">

      <div ng-repeat="name in c.names | filter:name" ng-init="c.count = $index + 1;">
          {{name}}
      </div>
      <div ng-repeat="name in c.names2 | filter:name"  ng-init="c.count2 = $index + 1;">
          {{name}}
      </div>
    </div>
  </body>
</html>

Javascript:

var app = angular.module('app', []);
app.controller('ctrl', function(){
  var c = this;
  c.count = 0;
  c.names = ['jim', 'james', 'fred', 'lue'];
  c.names2 = ['jim2', 'james2', 'fred2', 'lue2'];
});

Upvotes: 2

Views: 124

Answers (1)

Dylan
Dylan

Reputation: 4773

Set a filtered array as a temp variable and count it.

Plunker

<div ng-controller="ctrl as c">

<h1>Count: {{c.filtered1.length + c.filtered2.length}}</h1>
Search by name:
<input type="text" ng-model="name">

<div ng-repeat="name in c.filtered1 = (c.names | filter:name)">
  {{name}}
</div>

<div ng-repeat="name in c.filtered2 = (c.names | filter:name)">
  {{name}}
</div>

</div>

Upvotes: 1

Related Questions