Home >Web Front-end >JS Tutorial >How to Count Filtered Data in AngularJS's ng-repeat?

How to Count Filtered Data in AngularJS's ng-repeat?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-11 15:53:031031browse

How to Count Filtered Data in AngularJS's ng-repeat?

Count Filtered ng-repeat Data

When utilizing AngularJS's ng-repeat directive to display data, it is essential to understand how to accurately count the number of filtered results.

Consider the following scenario:

var data = [
  {
    "name": "Jim",
    "age": 25
  },
  {
    "name": "Jerry",
    "age": 27
  }
];

To display the data filtered by a user query, the following code can be used:

<div ng-repeat="person in data | filter: query"></div>

However, the default count of displayed elements ({{data.length}}) will always reflect the total number of items in the original array, regardless of the filter applied. To obtain an accurate count of the filtered results, there are several options:

Angular 1.3

  • Use an alias expression:
<div ng-repeat="person in data | filter: query as filtered"></div>

Angular Prior to 1.3

  • Assign the filtered results to a new variable:
<div ng-repeat="person in filtered = (data | filter: query)"></div>

The filtered count can then be displayed as:

Showing {{filtered.length}} Persons

The above is the detailed content of How to Count Filtered Data in AngularJS's ng-repeat?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn