angularjs 具有排除选项的过滤器('filter')

angularjs filter('filter') with exclude option

我有一个 json 对象数组,如下所示:

$scope.data = [{ name: "something something", date: 982528 }, 
               { x: 1, y: { sub: 2}, prop1: "some string" }, 
               { a: "b", c: "d", e: "some string" }];

我正在尝试使用以下方法对其进行过滤:

var filteredData = $filter('filter')($scope.data, "some string");

这样在数组中对象的所有属性中,angular与搜索字符串进行比较,

在此示例中,它将 return 最后两个对象,

现在,我需要传递一组属性,例如:

var exclude =  ['prop1'];

所以过滤器将忽略比较每个对象中的那些属性, 是否有带此选项的 angular 过滤器?

很遗憾,您应该创建自定义 excludeFilter:

angular.module('app', []).controller('ctrl', function($scope){
  $scope.data = [
    { name: "something something", date: 982528 }, 
    { x: 1, y: { sub: 2}, prop1: "some string", prop2: "some string" }, 
    { a: "b", c: "d", e: "some string" }
  ];  
  $scope.search = 'some';
  $scope.exclude = ['prop1', 'prop2'];
}).filter('excludeFilter', function(){
  return function(data, search, exclude){
    if(!search)
      return data;
    return data.filter(function(x){
      for(var prop in x)
        if(exclude.indexOf(prop) == -1){           
           var value = x[prop];
           if(value.indexOf && value.indexOf(search) != -1)
              return true;
           if(!value.indexOf && value == search)
              return true;
        }          
      return false;
    });
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>

<div ng-app='app' ng-controller='ctrl'>
  search: <input type='text' ng-model='search'/>  
  <br>
  exclude: <input type='text' ng-model='exclude' ng-list/>    
  <ul>
    <li ng-repeat='x in data | excludeFilter : search : exclude'>{{x | json}}</li>
  </ul>
</div>