Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS Trying to find the total length of a filtered array that uses limitTo

So I'm trying to get the total length of a filtered array in AngularJS after I've used LimitTo to keep the app from displaying more than a certain amount of elements at a time. The code is as follows:

<span>Results: {{filtered.length}}</span>
<li ng-repeat = "element in filtered = (array | filter:selectedTag | limitTo:load.number)">

I'm expecting about 150 total results but I'm keeping it limited to displaying 25 at a time. I want the Results to show the total length of the filtered array rather than just the limited version. Is there angular code to be able to get that without running the filter again?

like image 387
user3235995 Avatar asked Dec 08 '22 10:12

user3235995


2 Answers

You're allowed to create a new variable on-the-fly, right inside the ng-repeat expression. This new variable can hold a reference to filtered results and it can be used outside of ng-repeat:

PLUNKER DEMO

<div>Total: {{array.length}}</div>
<div>Filtered: {{filtered.length}}</div>

<ul>
  <li ng-repeat="element in (filtered = (array | filter:selectedTag)) | limitTo:load.number">
      {{element}}
  </li>
</ul>

This way the filtering loop will run only once.

like image 113
Stewie Avatar answered Dec 11 '22 11:12

Stewie


Unfortunately there is no way to avoid running the filter twice without writing some javascript to assign the result of the filter to a variable.

So, one solution would be to run the selectedTag filter in your controller whenever your array changes, store that locally and use it in your view.

Add this code to your controller:

.controler($scope, $filter) {
    // Existing code
    $scope.array = ...
    $scope.selectedTag = ...

    // New code
    $scope.filteredArray = [];

    $scope.$watchCollection('array', function (array) {
        $scope.filteredArray = $filter('filter')(array, $scope.selectedTag);
    });
}

And in your view:

<span>Results: {{filteredArray.length}}</span>
<li ng-repeat = "element in filteredArray | limitTo:load.number">

References - http://docs.angularjs.org/api/ng.filter:filter

like image 24
oztune Avatar answered Dec 11 '22 11:12

oztune