How to display length of filtered ng-repeat data
For Angular 1.3+ (credits to @Tom)
Use an alias expression (Docs: Angular 1.3.0: ngRepeat, scroll down to the Arguments section):
<div ng-repeat="person in data | filter:query as filtered">
</div>
For Angular prior to 1.3
Assign the results to a new variable (e.g. filtered
) and access it:
<div ng-repeat="person in filtered = (data | filter: query)">
</div>
Display the number of results:
Showing {{filtered.length}} Persons
Fiddle a similar example. Credits go to Pawel Kozlowski
For completeness, in addition to previous answers (perform calculation of visible people inside controller) you can also perform that calculations in your HTML template as in the example below.
Assuming your list of people is in data
variable and you filter people using query
model, the following code will work for you:
<p>Number of visible people: {{(data|filter:query).length}}</p>
<p>Total number of people: {{data.length}}</p>
-
{{data.length}}
- prints total number of people -
{{(data|filter:query).length}}
- prints filtered number of people
Note that this solution works fine if you want to use filtered data only once in a page. However, if you use filtered data more than once e.g. to present items and to show length of filtered list, I would suggest using alias expression (described below) for AngularJS 1.3+ or the solution proposed by @Wumms for AngularJS version prior to 1.3.
New Feature in Angular 1.3
AngularJS creators also noticed that problem and in version 1.3 (beta 17) they added "alias" expression which will store the intermediate results of the repeater after the filters have been applied e.g.
<div ng-repeat="person in data | filter:query as results">
<!-- template ... -->
</div>
<p>Number of visible people: {{results.length}}</p>
The alias expression will prevent multiple filter execution issue.
I hope that will help.
The easiest way if you have
<div ng-repeat="person in data | filter: query"></div>
Filtered data length
<div>{{ (data | filter: query).length }}</div>
ngRepeat creates a copy of the array when it applies a filter, so you can't use the source array to reference only the filtered elements.
In your case, in may be better to apply the filter inside of your controller using the $filter
service:
function MainCtrl( $scope, filterFilter ) {
// ...
$scope.filteredData = myNormalData;
$scope.$watch( 'myInputModel', function ( val ) {
$scope.filteredData = filterFilter( myNormalData, val );
});
// ...
}
And then you use the filteredData
property in your view instead. Here is a working Plunker: http://plnkr.co/edit/7c1l24rPkuKPOS5o2qtx?p=preview