aron.duby aron.duby - 4 months ago 67
AngularJS Question

angular ng-repeat skip an item if it matches expression

I'm looking for a way to basically tell angular to skip an item in an ng-repeat if it matches an expression, basically

continue
;

In controller:

$scope.players = [{
name_key:'FirstPerson', first_name:'First', last_name:'Person'
}, {
name_key:'SecondPerson', first_name:'Second', last_name:'Person'
}]


Now in my template I want to show everyone that doesn't match
name_key='FirstPerson'
. I figured it has to be filters so I setup a Plunkr to play around with it but haven't had any luck. Plunkr Attempt

Answer

As @Maxim Shoustin suggested, the best way to achieve what you want would be to use a custom filter.
But there are other ways, one of them being to use the ng-if directive on the same element were you put the ng-repeat directive (also, here's the plunker):

<ul>
    <li ng-repeat="player in players" ng-if="person.name_key!='FirstPerson'"></li>
</ul>

This may present a minor disadvantage from an estetical perspective, but has a major advantage that your filtering could be based on a rule that is not as tight coupled to the players array and that can easily access other data in your app's scope:

  <li 
      ng-repeat="player in players" 
      ng-if="app.loggedIn && player.name != user.name"
  ></li>

Update
As stated, this is one of the solutions for this kind of problem and may or may not suit your needs.
As pointed out in the comments, ng-if is a directive, which actually means that it might do more things in the background than you might expect.
For example, ng-if creates a new scope from it's parent:

The scope created within ngIf inherits from its parent scope using prototypal inheritance.

This usually doesn't affect the normal behaviour but in order to prevent unexpected cases, you should keep this in mind before implementing.

Comments