aron.duby aron.duby - 1 year ago 159
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


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

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):

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

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:

      ng-repeat="player in players" 
      ng-if="app.loggedIn && !="

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download