AngularJS在多个字段上过滤ng-repeat OR

时间:2018-05-04 12:11:15

标签: angularjs filter

如何在OR语句中组合它们的不同字段中过滤一个搜索词?

<ul>
    <li ng-repeat="person in persons| filter:filters{surname: 'foo' OR name: 'foo'}">
        {{person}}
    </li>
</ul>

1 个答案:

答案 0 :(得分:2)

您可以使用| filter:'foo'过滤每个对象的所有属性,也可以创建自定义过滤器,例如

&#13;
&#13;
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
  $scope.persons=[
    {"id":1,"name":"foo","surname":"bar"},
    {"id":2,"name":"baz","surname":"foo"},
    {"id":3,"name":"null","surname":"undefined"},
    {"id":4,"name":"name","surname":"surname"}
  ]
});
app.filter('searchBy', function() {
  return function(array, param) {
    var new_array = [];
    angular.forEach(array, function(value) {
      if (value.name == param || value.surname == param) { // your filter query in here
        new_array.push(value);
      }
    })
    return new_array;
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>

<div ng-app="myApp" ng-controller="myCtrl">
  <ul>
    <li ng-repeat="person in persons| searchBy:'foo'">
      {{person}}
    </li>
  </ul>
</div>
&#13;
&#13;
&#13;