How can I show a count of rows from an ng-repeat?

All we need is an easy explanation of the problem, so here it is.

I have a table on my web page that is populated with data like this:

<tr data-ng-repeat="row in grid.data | filter:isQuestionInRange">
   <td>{{ row.problemId }}</td>
</tr>

Is there a way that I can put a count of the rows displayed in the table footer. Note that I want to be able to show the rows after that have been filtered not just the row count from the grid.data array.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can store the results of the filter and then get the length of that, for example using results here:

<tr data-ng-repeat="row in results = (grid.data | filter:isQuestionInRange)">
   <td>{{ row.problemID }}</td>
</tr>
{{results.length}}

This has the performance advantage of only needing to run the filter once. It’s also handy for other situations where you need both filtered and unfiltered results within your ng-repeat.

Method 2

You could check the length of the filtered array such as:

{{ (grid.data | filter:isQuestionInRange).length }}

Method 3

I suggest that you use the $filter service in your controller, like shown in this example plunk:

$scope.evenNumbers = $filter('filter')($scope.numbers, $scope.isEven);

In your case:

var $scope.filteredRows = $filter('filter')($scope.gridData, $scope.isQuestionInRange);

This way you do the filtering only once and avoid to introduce new scope fields in the template which makes your code hard to test and to understand.

You repeat over filteredRows in your template and {{ filteredRows.length }} gives you the number of visible rows.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply