使用AngularJS ng-repeat过滤器匹配多个结果?

时间:2013-11-27 05:08:34

标签: angularjs

我已将ng-model附加到< select>在AngularJS中缩小我的数据集的结果:

<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>

目前这个过滤器显示的食物既可以是与过滤器匹配的水果颜色,但我就像过滤器一样,无论颜色如何都能匹配水果它们是在选择水果并选择颜色时选择“颜色”(以及在选择颜色时选择与果实选择的“水果”无关的颜色)。我可以这样做吗?谢谢!

1 个答案:

答案 0 :(得分: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-repeat过滤器。 * search_terms是存储两个条件选择器值的数据对象。

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

我认为当你想渲染select元素的选项时,你应该使用ng-options而不是ng-repeat。 ng-repeat会导致一些问题:

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

希望这对你有所帮助。