Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 562
Fyodor Khruschov Avatar asked Oct 29 '13 17:10

Fyodor Khruschov


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.

What can I use instead of NG-repeat?

But ng-repeat is not the right thing to use when you have large datasets as it involves heavy DOM manipulations. And you should consider using ng-repeat with pagination. You can consider using transclusion inside a custom directive, to achieve the behavior you are looking for without using ng-repeat.

How do I get an index value 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.

How do you use two ng-repeat in a table?

NEST TWO ng-repeatThe first ng-repeat in the tr tag will create the rows and the second one in the td tag will create one column per element in the collection. By using one ng-repeat for the row and an other for the column, the rows and the columns of your table is now driven by a subset.


2 Answers

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> 
like image 133
Stewie Avatar answered Oct 10 '22 08:10

Stewie


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> 
like image 26
dnc253 Avatar answered Oct 10 '22 08:10

dnc253