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

时间:2018-03-21 23:17:02

标签: angularjs angularjs-filter

我有一个像这样的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与搜索字符串进行比较,

在这个例子中,它将返回las两个对象,

现在,我需要传递一系列属性,如:

var exclude =  ['prop1'];

所以过滤器将省略比较每个对象中的那些属性, 有这个选项的角度过滤器吗?

1 个答案:

答案 0 :(得分:1)

不幸的是,您应该创建自定义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>
&#13;
&#13;
&#13;