ng-show if过滤数组是否包含

时间:2016-03-24 22:53:27

标签: javascript angularjs

只有当数组在其对象中包含特定值时,才能找到显示html元素的方法。 如果我有:

people[
    {
        id:1, name: 'frank', type: 'good'
        ,id:2, name: 'john', type: 'bad'
        ,id:3, name: 'mary', type: 'good'
    }
]

我想展示某种类型的标题。 所以,如果类型是:

"great"
"good"
"bad"

使用上面的数组,“great”的标题不应该是可见的。

我尝试过使用ngif和ngshow。问题似乎与语法有关。 我尝试的最后一个是:

(people|filter:(type:'great'))

但我在控制台中收到错误。

是否可以直接在html中修复它,还是应该依靠控制器进行这种操作?

1 个答案:

答案 0 :(得分:1)

首先,您的示例“数组”形成错误,我假设您的意思是:

people = [
    { id:1, name: 'frank', type: 'good' },
    { id:2, name: 'john',  type: 'bad' },
    { id:3, name: 'mary',  type: 'good' }
];

其次,你的问题有点令人困惑,但我假设你想要在与其类型对应的标题下显示每个人,并隐藏没有人的标题。试试这个:

<div ng-if="$filter('filter')(people,{type:'great'}).length > 0">
    <h1>Great</h1>
    <p ng-repeat="person in people | filter:{type:'great'}">{{person.name}}</p>
</div>
<div ng-if="$filter('filter')(people,{type:'good'}).length > 0">
    <h1>Good</h1>
    <p ng-repeat="person in people | filter:{type:'good'}">{{person.name}}</p>
</div>

您可以通过创建第二个数组来改进这一点:

types = [
    { id: 'great', header: 'Great' },
    { id: 'good',  header: 'Good' },
    { id: 'bad',   header: 'Bad' }
];

然后只是嵌套你的重复:

<div ng-repeat="type in types" ng-if="$filter('filter')(people,{type:type.id}).length > 0">
    <h1>{{type.header}}</h1>
    <p ng-repeat="person in people | filter:{type:type.id}">{{person.name}}</p>
</div>
  • 请注意,我还没有测试过这段代码,只是查看过了。它可能包含错误,但该方法应该有效。
  • 您需要添加$ filter作为控制器的依赖项,并将其注入

TL / DR是: $ filter服务允许您在JS表达式中使用Angular过滤器。 “过滤器”过滤器会返回一个数组,因此请过滤您的人并检查长度。

相关问题