20

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?

itsme
  • 48,972
  • 96
  • 224
  • 345

2 Answers2

52

Use ng-if (or 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.

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:

<div ng-repeat="i in values">
   <div ng-if="$first"></div>
</div>
Davin Tryon
  • 66,517
  • 15
  • 143
  • 132
  • 2
    ng-if is a better solution than ng-show because ng-if modifies the DOM. ng-show only shows/hides the element. – RaviH Jan 25 '14 at 14:49
  • @RaviH yes, that is why the example uses ng-if. But, they are both valid solutions based on what you are trying to achieve. – Davin Tryon Jan 25 '14 at 14:50
  • @DavinTryon hey thank you , do you know man how can i put an incremental var in this same loop ? :P i would like to show a div inside loop only if increment%3 === 0 for example but i can't find out how :( – itsme Jan 25 '14 at 14:53
  • 3
    @sbaaaang There is one built in to ng-repeat: `$index`. You've also got `$odd` and `$even` to do things like alternate rows. – Davin Tryon Jan 25 '14 at 14:54
  • yeah, that should do it. – Davin Tryon Jan 25 '14 at 14:55
  • http://stackoverflow.com/questions/21869283/when-to-favor-ng-if-vs-ng-show-ng-hide – Stephan Kristyn Sep 08 '14 at 14:54
  • I think better to use a filter, because i hope (didn't check) that $index will have real element index (like filtered array index). If we use ng-if (that actually simplest solution that can came into mind), we will have problems with $index, because there would be hidden elements that would considered by $index as well. http://stackoverflow.com/questions/18056241/angular-ng-repeat-with-condition – Rantiev Jul 15 '15 at 14:25
9

Use the ng-if statement

<div ng-repeat="i in values">
   {{i}}
   <div ng-if="i !== 0"></div>
</div>
StarsSky
  • 6,721
  • 6
  • 38
  • 63