kalim sayyad
kalim sayyad

Reputation: 1086

Function called infinitely in ng-repeat block

I have a controller in which i am displaying a list on the page. I have to eliminate few list items based on some flags present in it. So I have written a simple function which will return a boolean value and will use this value in the ng-show directive to hide the items. The function is called multiple times in the ng-repeat block. My understanding is that if my array length is n then function should be called n times only unless the array contents/length is changed.

<ul>
<li ng-repeat="item in items" ng-show="display(item)">{{item.name}}</li>
</ul>

My display function would look like this

display = function(item)
{
    if(item.flag) 
       return true
    else 
       return false;
}

Upvotes: 1

Views: 140

Answers (2)

daxeh
daxeh

Reputation: 1085

I will try to ensure that any function call is within controller scope

ie. $scope.display however, the following might help to make it clearer.

<!-- iterate elements in items, ie. {name: "a", flag: true} -->
<ul>
  <li ng-repeat="item in items" ng-show="item.flag">{{item.name}}</li>
</ul>

and without a function call since, ng-show reads boolean from item.flag

  $scope.items = [
    {name: "a", flag: true},
    {name: "b", flag: true},
    {name: "c", flag: false}
  ];

and the output is..

a
b

Hope this helps.

Upvotes: 1

Iso
Iso

Reputation: 3238

You can use Angular’s built-in filter filter:

<li ng-repeat="item in items | filter: { flag: true }">{{item.name}}</li>

Upvotes: 0

Related Questions