2

I have a simple ng-repeat that displays only half of the items. For some reason, i got it to work with ng-show but not with ng-if. I don't understand why?

this works:

<li ng-repeat="item in items" ng-show="$index < items.length / 2">{{item}}</li>

this doesn't:

  <li ng-repeat="item in items" ng-if="$index < items.length / 2">{{item}}</li>

here is a jsfiddle to demonstrate: http://jsfiddle.net/HB7LU/17269/

This question: AngularJS: ng-if not working in combination with ng-click? does not provide an answer why ng-show works while ng-if doesn't

Community
  • 1
  • 1
Moshe Shaham
  • 15,448
  • 22
  • 74
  • 114
  • Possibly relevant: http://stackoverflow.com/questions/19812116/angularjs-ng-if-not-working-in-combination-with-ng-click – CollinD Sep 05 '15 at 20:07
  • 2
    try using a higher version that angular 1.01 and also use valid html. `

    ` is not valid child of `

      `
    – charlietfl Sep 05 '15 at 20:08
  • 1
    Solved by updating the angular version: http://jsfiddle.net/HB7LU/17271/ While we have the chance to speak, why on earth did you update this jsfiddle **17269** times!? Don't click Update unless you want to share the fiddle with its current state, Run is enough for updating the fiddle. – gdoron Sep 05 '15 at 20:09

1 Answers1

1

I'm guessing this is because of the Angular's priority rendering cycle. They might've changed its behavior with newer versions as someone posted above. In case like yours I usually make a custom filter for ngRepeat to slice the array and show only specified number of items based on the offset (ngRepeat pagination). I've never messed up with using ngRepeat directly with ngIf or ngShow/Hide as it can get really bugged whichever way you turn it.

  • ngRepeat directive creates and appends new node elements.
  • ngShow will allow angular to generate an element, but after that it will set it's display to none.
  • ngIf won't allow angular to generate an element.

As far as I know, ngIf has higher priority than ngRepeat, so I can assume that what's happening below the field is:

  • Angular sees the array.
  • ngIf doesn't know what $index (as it's part of ngRepeat) is so its cycle just runs by.
  • ngRepeat renders elements.

whilst ngShow works:

  • Angular sees the array.
  • ngRepeat renders elements.
  • ngShow shows them by specified condition.
Davion
  • 881
  • 6
  • 12