当前位置: 动力学知识库 > 问答 > 编程问答 >

How to filter multiple values (OR operation) in angularjs if filter is false

问题描述:

Have some trouble with multiple filters. One filter works good, if add second filter ng-repeat get filters with operator AND, but I need take second filter if first is 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>

网友答案:

For this you will need to create a simple filter function in controller. The usage could be something like this for example:

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

Here is a demo:

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;
    };  
  };
}
<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>
分享给朋友:
您可能感兴趣的文章:
随机阅读: