【问题标题】:angularjs filter('filter') with exclude option带有排除选项的 angularjs 过滤器(“过滤器”)
【发布时间】:2018-03-21 23:17:01
【问题描述】:

我有一个这样的 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");

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

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

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

var exclude =  ['prop1'];

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

【问题讨论】:

  • 你不能排除属性,但是你可以传递一个对象来定义你想要包含的属性;即$filter('filter')($scope.data, {e: "some string"}); 只会返回e === "some string" 的对象,但不会与其他属性匹配。见docs.angularjs.org/api/ng/filter/filter
  • @Claies mmm 问题是那些 json 对象是 biiiiiiig,每个至少有 50 个属性,我最多只需要排除 4 个......

标签: angularjs angularjs-filter


【解决方案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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多