Angular JS - ng-repeat和循环条件

时间:2022-08-23 23:40:55

Hey i have this piece of code:

嘿,我有这段代码:

<div ng-repeat="i in values">
{{i}}
</div>

It works but i would like to put extra conditions inside the loop something like:

它的工作原理,但我想在循环中添加额外的条件,如:

<div ng-repeat="i in values">
{{i}}
if(i !== 0){
<div></div>
}
</div>

How can i achieve this?

我怎样才能做到这一点?

2 个解决方案

#1


52  

Use ng-if (or ng-show):

使用ng-if(或ng-show):

<div ng-repeat="i in values">
   <div ng-if="i !== 0"></div>
</div>

Attached to the element, this will decide whether to display it or not.

附加到元素,这将决定是否显示它。

Documentation for ng-if can be found here.

可在此处找到ng-if的文档。

However, if you want to only do something if you are looping the first or last item, you can use $first and $last properties of ng-repeat as well. These are documented with ng-repeat. And can be used like this:

但是,如果您只想循环第一个或最后一个项目,那么您也可以使用ng-repeat的$ first和$ last属性。这些都用ng-repeat记录。并且可以像这样使用:

<div ng-repeat="i in values">
   <div ng-if="$first"></div>
</div>

#2


9  

Use the ng-if statement

使用ng-if语句

<div ng-repeat="i in values">
   {{i}}
   <div ng-if="i !== 0"></div>
</div>

#1


52  

Use ng-if (or ng-show):

使用ng-if(或ng-show):

<div ng-repeat="i in values">
   <div ng-if="i !== 0"></div>
</div>

Attached to the element, this will decide whether to display it or not.

附加到元素,这将决定是否显示它。

Documentation for ng-if can be found here.

可在此处找到ng-if的文档。

However, if you want to only do something if you are looping the first or last item, you can use $first and $last properties of ng-repeat as well. These are documented with ng-repeat. And can be used like this:

但是,如果您只想循环第一个或最后一个项目,那么您也可以使用ng-repeat的$ first和$ last属性。这些都用ng-repeat记录。并且可以像这样使用:

<div ng-repeat="i in values">
   <div ng-if="$first"></div>
</div>

#2


9  

Use the ng-if statement

使用ng-if语句

<div ng-repeat="i in values">
   {{i}}
   <div ng-if="i !== 0"></div>
</div>