在Angular.js的ng-repeat指令中的if语句

时间:2022-07-07 19:43:01

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:

我正在尝试将if转换为ng-repeat指令,但我很难。我现在工作的代码是:

<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.

谢谢。

2 个解决方案

#1


34  

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

正如我在评论中写的那样,您可以使用过滤器来实现这一点。这是一个例子: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}"

#2


10  

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.

我添加了一个plnkr作为例子。

#1


34  

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

正如我在评论中写的那样,您可以使用过滤器来实现这一点。这是一个例子: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}"

#2


10  

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.

我添加了一个plnkr作为例子。