您可以定義自定義過濾器這樣的:
$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-重複會造成一些問題:
<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。
希望這對你有所幫助。
自定義過濾器? – AlwaysALearner