angular ng-repeat 跳过与表达式匹配的项目 [英] angular ng-repeat skip an item if it matches expression

查看:17
本文介绍了angular ng-repeat 跳过与表达式匹配的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法,如果它与表达式匹配,基本上告诉 angular 跳过 ng-repeat 中的项目,基本上 continue;

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;

在控制器中:

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

现在在我的模板中,我想向所有不匹配 name_key='FirstPerson' 的人展示.我认为它必须是过滤器,所以我设置了一个 Plunkr 来玩它,但没有任何运气.Plunkr 尝试

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

推荐答案

正如 @Maxim Shoustin 所建议的那样,实现您想要的最佳方式是使用自定义过滤器.
但是还有其他方法,其中一种方法是在同一元素上使用 ng-if 指令,如果您放置了 ng-repeat 指令(此外,这里是 plunker):

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>

从美学的角度来看,这可能是一个次要的缺点,但有一个主要的优点,即您的过滤可以基于与 players 数组没有那么紧密耦合并且可以轻松访问的规则您的应用范围内的其他数据:

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>

更新
如上所述,这是针对此类问题的解决方案之一,可能满足也可能不满足您的需求.
正如评论中指出的那样,ng-if 是一个指令,这实际上意味着它可能在后台做的事情比你想象的要多.
例如,ng-if 从其父作用域创建一个新作用域:

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:

ngIf 中创建的作用域使用原型继承从其父作用域继承.

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.

这篇关于angular ng-repeat 跳过与表达式匹配的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆