2013-11-27 62 views
0

我已經附加NG-模型<選擇AngularJS >縮小我的數據集的結果,例如:使用AngularJS ng-repeat過濾器匹配多個結果?

<select ng-model="search_terms.fruit"> 
<option>Fruit</option> 
<option ng-repeat="fruit in search_fruits">{{ fruit }}</option> 
</select> 
<select ng-model="search_terms.color"> 
<option>Color</option> 
<option ng-repeat="color in search_colors">{{ color }}</option> 
</select> 

...

<div ng-repeat="food in foods | filter:{fruit:search_terms.fruit, color:search_terms.color} | orderBy:orderProp">...</div> 

目前此過濾器顯示的食物,都水果顏色匹配過濾器,但我會喜歡過濾器來匹配的水果,無論他們是什麼顏色,當水果被選中和「顏色」選擇的顏色(以及匹配當選擇顏色時選擇水果顏色,爲水果選擇「水果」)。我可以這樣做嗎?謝謝!

+0

自定義過濾器? – AlwaysALearner

回答

1

您可以定義自定義過濾器這樣的:

$scope.customFilter = function(searchTerm){ 
    return function(food){ 
     //if only one condition is selected 
     if(searchTerm.color===null||searchTerm.fruit===null) 
     { 
     return food.fruit==searchTerm.fruit||food.color==searchTerm.color; 
     }else{ 
     return food.fruit==searchTerm.fruit&&food.color==searchTerm.color; 
     } 
    }; 
}; 

添加應用到你的NG-重複過濾器。 * search_terms是存儲兩個條件選擇器值的數據對象。

<div ng-repeat="food in foods | filter:customFilter(search_terms)">{{food.name}}</div> 

我想你應該用ng-options代替ng-repeat,當你想渲染select元素的選項。 NG-重複會造成一些問題:

enter image description here

<select ng-model="search_terms.fruit" ng-options="fruit for fruit in search_fruits"> 
    <option value="">fruit</option> 
</select> 

我的實現:

HTML

<div ng-controller="myCtrl"> 
    <select ng-model="search_terms.fruit" ng-options="fruit for fruit in search_fruits"> 
    <option value="">fruit</option> 
    </select> 
    <select ng-model="search_terms.color" ng-options="color for color in search_colors"> 
    <option value="">color</option> 
    </select> 

    <h3>RESULT</h3> 
    <div ng-repeat="food in foods | filter:customFilter(search_terms)">{{food.name}}</div> 
</div> 

JS

angular.module("app",[]) 
.controller("myCtrl",function($scope){ 
    $scope.search_fruits = ["Apple","Orange","Lemon"]; 
    $scope.search_colors = ["Red","Yello","Green"]; 
    $scope.foods = [{name:"Apple Pie",fruit:"Apple",color:"Red"},{name:"Lemon tea",fruit:"Lemon",color:"Yello"}]; 
    $scope.search_terms={color:null,fruit:null}; 

    $scope.customFilter = function(searchTerm){ 
    return function(food){ 
     //if only one condition is selected 
     if(searchTerm.color===null||searchTerm.fruit===null) 
     { 
     return food.fruit==searchTerm.fruit||food.color==searchTerm.color; 
     }else{ 
     return food.fruit==searchTerm.fruit&&food.color==searchTerm.color; 
     } 
    }; 
    }; 
}); 

這是jsFiddle DEMO

希望這對你有所幫助。