Fyodor Khruschov
Fyodor Khruschov

Reputation: 1717

Angular.js. How to count ng-repeat iterations which satisfy the custom filter

Here's my code:

<div ng-show="?" ng-repeat="item in items | notEmpty">
</div>

Filter:

Kb.filter("notEmpty", function(){ 
  return function(input){
    var output=[];
    for(var i=0;i<input.length;i++){
      if(input[i]){
        output.push(input[i]);
      }
    }
    return output;
}});

I need to show/hide repeated s according the quantity of filtered items in the loop. What is the best way to do it?

Thanks

Upvotes: 21

Views: 68195

Answers (4)

Ga&#235;l J
Ga&#235;l J

Reputation: 15090

As of Angular 1.3 you can use following syntax for ng-repeat:

variable in expression as alias_expression

That is:

<p>Number of filtered items: {{filteredItems.length}}</p>

<div ng-repeat="item in items | notEmpty as filteredItems">
 ...
</div>

Upvotes: 2

Sajjad Ali Khan
Sajjad Ali Khan

Reputation: 1813

I found this

How to display length of filtered ng-repeat data ,

that describes to get the count after filtering the list

Upvotes: 0

Stewie
Stewie

Reputation: 60406

ng-repeat expression allows filtered results to be assigned to a variable. This variable will be accessible from current scope so you can use it in same scope anyway you want:

<p>Number of filtered items: {{filteredItems.length}}</p>

<div 
  ng-show="filteredItems.length > 0" 
  ng-repeat="item in filteredItems = (items | notEmpty)"
>
 {{$index}}
</div>

Upvotes: 60

dnc253
dnc253

Reputation: 40337

The easiest way may be to run the filter in your controller. Something like this:

function MyCtrl($scope, notEmptyFilter)
{
    //$scope.items is put into the scope somehow
    $scope.filteredItems = notEmptyFilter($scope.items);
}

Then your HTML would look something like this:

<div ng-show="filteredItems.length > 0" ng-repeat="item in filteredItems">
</div>

Upvotes: 2

Related Questions