2014-02-12 54 views
11

我需要能夠過濾對象的一個​​字段的兩個不同值。以下面的例子。對一個字段的多個值使用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

回答

22

使用過濾器函數:

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

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

Fiddle

0
<!-- 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'; 
};