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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With