Samantha J T Star
Samantha J T Star

Reputation: 32808

How can I watch the number of elements in a filtered ng-repeat?

I have the following ng-repeat?

<table>
<tr data-ng-repeat="row in grid.data | filter:isProblemInRange>
<td>xxx</td>
</tr>
</table>

The rows are filtered with isProblemInRange function which is based on the value of two input fields. Depending on what I put in these fields the number of rows displayed can change.

Is it possible for me to do a watch on the number of rows that are present on the screen and if so how can I do this from inside my controller?

Upvotes: 3

Views: 102

Answers (3)

m.e.conroy
m.e.conroy

Reputation: 3538

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

$scope.$watch('filteredRows',function(newVal,oldVal){
    if(!angular.equals(newVal.length,oldVal.length)){
        [... Do stuff here when the number of filtered rows changes ...]
    }
});

$scope.$watch('gridData',function(newVal,oldVal){
    if(!angular.equals(newVal,oldVal)){
        $scope.filteredRows = $filter('filter')($scope.gridData, $scope.isProblemInRange);
    }
});

Upvotes: 0

lex82
lex82

Reputation: 11317

You can use the $filter service in your controller:

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

and run the ng-repeat over the filtered rows. This way you avoid to introduce new scope fields in the template which makes your code hard to test and to maintain.

See this plunk for an example.

Upvotes: 0

Variant
Variant

Reputation: 17365

Have a look at the solution here: https://stackoverflow.com/a/19956685/340128

The defined variable results is appended to the scope and can be accessed from the controller as well.

Upvotes: 2

Related Questions