AngularJS过滤一个字段的多个值

时间:2014-02-12 18:29:12

标签: javascript angularjs

我需要能够过滤对象的一个​​字段的两个不同值。以下面的例子为例。

$scope.products = [
    {name:"Apple",type:"fruit"},
    {name:"Grape",type:"fruit"},
    {name:"Orage",type:"fruit"},
    {name:"Carrot",type:"vegetable"},
    {name:"Milk",type:"dairy"}
]

使用过滤器ng-repeat="item in products | filter:{type:'fruit'}"。我可以获得所有的成果。但如果我想要所有的水果和蔬菜怎么办呢。我试过了

ng-repeat="item in products | filter:{type:['fruit','vegetable']}"

但那没用。我认为应该有一个简单的解决方案,但我找不到它。

JSFiddle Example

2 个答案:

答案 0 :(得分:23)

使用过滤功能:

$scope.fruitOrVeg = function(product){
    return product.type == 'fruit' || product.type == 'vegetable';
};

<li ng-repeat="item in products | filter:fruitOrVeg">{{item.name}}</li>

<强> Fiddle

答案 1 :(得分:-1)

<!-- you can also use a function this simpler way-->

<div ng-repeat="product in products | filter: myFilter">

$scope.myFilter = function (item) { 
   return product.type == 'fruit' || product.type == 'vegetable';
};