Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display length of filtered ng-repeat data

I have a data array which contains many objects (JSON format). The following can be assumed as the contents of this array:

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

Now, I display these details as:

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

Here, query is modeled to an input field in which the user can restrict the data displayed.

Now, I have another location in which I display the current count of people / person being display, i.e Showing {{data.length}} Persons

What I want to do is that when the user searches for a person and the data displayed is filtered based on the query, the Showing...persons also change the value of people being shown currently. But it is not happening. It always displays the total persons in data rather than the filtered one - how do I get the count of filtered data?

like image 548
user109187 Avatar asked Mar 09 '13 21:03

user109187


People also ask

How do I filter in NG-repeat?

The ng-repeat values can be filtered according to the ng-model in AngularJS by using the value of the input field as an expression in a filter. We can set the ng-model directive on an input field to filter ng-repeat values.

How do I get the index of an element in NG-repeat?

Note: The $index variable is used to get the Index of the Row created by ng-repeat directive. Each row of the HTML Table consists of a Button which has been assigned ng-click directive. The $index variable is passed as parameter to the GetRowIndex function.

Where is the last element in NG-repeat?

You can use $last variable within ng-repeat directive. Take a look at doc. Where computeCssClass is function of controller which takes sole argument and returns 'last' or null .

What is data ng-repeat?

The data-ng-repeat allows the HTML to be validated through validators that do not understand Angular. The documentation is here with directives. This is from the docs: Angular normalizes an element's tag and attribute name to determine which elements match which directives.


1 Answers

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

like image 193
Wumms Avatar answered Sep 28 '22 02:09

Wumms