Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement within a ng-repeat directive on Angular.js

I am trying to implement an if into a ng-repeat directive but I am having a hard time. my code which work for now is:

<p ng-repeat="list in lists">{{list[id].title}}</p>

What I want to do is basically

<p ng-repeat="list in lists if list[id].selected">{{list[id].title}}</p>

Of course, on the second line I am getting an error. Any advice on this?

Thank you.

like image 971
marceloduende Avatar asked Feb 06 '13 21:02

marceloduende


People also ask

How do you condition in NG-repeat?

You can add condition using ng-if also and this is effective too. You can apply any condition to your list using ng-if attribute. In below example, I have put condition where Age > 20 and IsActive is true. ng-repeat will fetch all records which full fill this scenario.

What does this directive do in AngularJS does ng-repeat?

AngularJS ng-repeat Directive The ng-repeat directive repeats a set of HTML, a given number of times. The set of HTML will be repeated once per item in a collection. The collection must be an array or an object. Note: Each instance of the repetition is given its own scope, which consist of the current item.

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.

What is NG-if in AngularJS?

AngularJS ng-if Directive The ng-if directive removes the HTML element if the expression evaluates to false. If the if statement evaluates to true, a copy of the Element is added in the DOM.


2 Answers

As I wrote in a comment, you could use filters to achieve that. Here's example: http://jsfiddle.net/sebmade/ZfGx4/44/

ng-repeat="list in lists | filter:myFilter"


And filter code:

$scope.myFilter = function(item) {
    return item.selected == true;
};


Edit:
I found that it is possible to do it with inline filter like this:

ng-repeat="list in lists | filter:{selected: true}"
like image 177
Jan.J Avatar answered Oct 21 '22 08:10

Jan.J


What you need to add here is a filter:

<p ng-repeat="list in lists | filter:{selected:true}">test {{list.title}}</p>

I've added a plnkr as an example.

like image 10
Shai Reznik - HiRez.io Avatar answered Oct 21 '22 08:10

Shai Reznik - HiRez.io