2016-03-24 28 views
0

我无法找到一种方法来显示一个html元素,只有当一个数组在对象中包含一个特定的值。 所以,如果我有:ng-show if filtered arrays contains

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

我想表现出某种的各类标题的。 所以如果类型:

"great" 
"good" 
"bad" 

与上面的阵列中,标题为“伟大”应该是不可见的。

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

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

但我在控制台得到一个错误。

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

+1

为什么不在'ng-show'表达式中使用'not'?例如:'people.type!='great'' – kazupooot

+1

http://plnkr.co/edit/xQBqLLhSDT2dhPrhVSWS?p=preview – kazupooot

+1

我不认为问题是如何使用Angular过滤器@kazupooot,而是如何根据过滤数组的结果做出决定。 OP,你能澄清吗? –

回答

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> 
  • 请注意,我没有测试了这个代码,只查看了一下。它可能包含错误,但该方法应该起作用。
  • 您需要$过滤器添加为控制器的依赖,并注入其

的TL/DR是:的$过滤器的服务让您在JS表达式中使用角过滤器。 '过滤器'过滤器返回一个数组,因此过滤你的人员并检查长度。