如果filter为false,如何在angularjs中过滤多个值(OR操作)

时间:2016-01-17 18:02:53

标签: angularjs angularjs-ng-repeat angular-filters

多个过滤器有问题。一个过滤器工作正常,如果添加第二个过滤器ng-repeat获取带有运算符AND的过滤器,但如果第一个为FALSE,我需要采用第二个过滤器。

function Ctrl($scope) {
  $scope.users = [
    {"id":1,"username":"", "age": "18"},
    {"id":8,"username":"betty", "age": ""},
    {"id":14,"username":"", "age": "18"},
    {"id":3,"username":"jumbo1", "age": ""},
  ]
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app>
  <div ng-controller="Ctrl">
    <div ng-repeat="user in filtered = (users | filter:{ 'username':'betty'}:true)">
      <span>{{ user.id }}</span>
    </div>  
  Users: {{users.length}}<br>
  Filtered Users: {{filtered.length}}    
  </div>
</body>

多个过滤器,例如,不起作用:

filter:{ 'username':'betty'} || { 'age':'18'}

最后需要第一个过滤器为FALSE采取第二个过滤器

1 个答案:

答案 0 :(得分:2)

为此,您需要在控制器中创建一个简单的过滤器功能。用法可能是这样的,例如:

users | filter:userFilter({username: 'betty', age: 18}

这是一个演示:

&#13;
&#13;
angular.module('demo', []).controller('Ctrl', Ctrl);

function Ctrl($scope) {
  $scope.users = [
    {"id":1,"username":"", "age": "18"},
    {"id":8,"username":"betty", "age": ""},
    {"id":14,"username":"", "age": "18"},
    {"id":3,"username":"jumbo1", "age": ""},
  ];
    
  $scope.userFilter = function(filter) {
    return function(user) {
      return user.username == filter.username || user.age == filter.age;
    };  
  };
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
<body ng-app="demo">
  <div ng-controller="Ctrl">
    <div ng-repeat="user in filtered = (users | filter:userFilter({username: 'betty', age: 18}))">
      <span>{{ user | json }}</span>
    </div>
    <pre>Users: {{users.length}}<br>Filtered Users: {{filtered.length}}</pre>    
  </div>
</body>
&#13;
&#13;
&#13;