在相同条件下过滤多个值

时间:2017-11-09 20:08:23

标签: angularjs angularjs-filter

无法找到答案。

说我有这个ng-repeat

<li ng-repeat="books in bookList | filter:color | filter:theme"></li>

还有多个按钮可根据颜色和主题过滤此列表。所以当我点击

 <a ng-click="color = {type: 1}">blue</a>

我用蓝色过滤所有元素。

但是现在我需要让用户按照他想要的过滤器,所以我想说他想用蓝色和黄色过滤。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:0)

创建自定义多值过滤器,如下所示:

&#13;
&#13;
angular
  .module("app", [])
  .controller("DemoCtrl", function($scope){
    $scope.selectedColors = ["blue", "red"];
    $scope.selectedThemes = ["t1", "t2"];
    $scope.items = [
      {
        color: "blue",
        theme: "t1"
      },
      {
        color: "blue",
        theme: "t2"
      },
      {
        color: "red",
        theme: "t2"
      },
      {
        color: "yellow",
        theme: "t3"
      }
    ];
   })
  .filter("multiValues", function(){
    return function(items, selectedValues, attrName) {
      var result = [];
      angular.forEach(items, function(item){
        if (selectedValues.indexOf(item[attrName]) > -1) {
          result.push(item);
        }
      });
      return result;
    }
  });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="DemoCtrl">
  <div>Before Filtering:</div>
  <ul ng-repeat="item in items">
    <li>{{item.color + " - " + item.theme}}</li>
  </ul>
  <div>Selected Colors: {{ selectedColors.join(", ") }}</div><br />
  <div>Selected Themes: {{ selectedThemes.join(", ") }}</div><br />
  <div>After Filtering:</div>
  <ul ng-repeat="item in items | multiValues:selectedColors:'color' | multiValues:selectedThemes:'theme'">
    <li>{{item.color + " - " + item.theme}}</li>
  </ul>
</div>
&#13;
&#13;
&#13;