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
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="player.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.
I know this is an old one, but in case someone would look for another possible solution, here is another way to solve this - use standard filter functionality:
Object: A pattern object can be used to filter specific properties on objects contained by array. For example {name:"M", phone:"1"} predicate will return an array of items which have property name containing "M" and property phone containing "1". ... The predicate can be negated by prefixing the string with !. For example {name: "!M"} predicate will return an array of items which have property name not containing "M".
So for the TS example something like this should do:
<ul> <li ng-repeat="player in players | filter: { name_key: '!FirstPerson' }"></li> </ul>
No need to write custom filters, no need to use ng-if
with it's new scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With