首页 > 解决方案 > 在逗号分隔的对象列和另一列上应用过滤器

问题描述

当我尝试在一个对象的多个列上应用过滤器时,我遇到了一个问题。我需要根据选定的下拉列表应用这些过滤器:一个下拉列表直接链接到 id,而另一个值包含名称,但必须根据列表列进行过滤。假设如果选择 def 它应该显示

1 def
2 ghi

我的数据将是

$scope.items =[
{ id: 1, list: ['abc','cde'], name: 'abc'},
{ id: 2, list: ['def','abc'], name: 'def'},
{ id: 3, list: ['def','ghi'], name: 'ghi'},
];

我的html代码是

<tr ng-repeat="item in items| filter:searchText">
{{item.id}} {{item.name}}
</tr>

由于必须在用户单击按钮时应用过滤器,因此将它们写在提交功能下;这是我在控制器中的过滤器代码:

$scope.filtr = {};
//$scope.filtr.id & $scope.filtr.list are the filters hold the value of drop-downs
$scope.submit = function() {
  for(prop in $scope.filtr) {
    $scope.searchText[prop] = $scope.filtr[prop];
  }
}

标签: angularjs

解决方案


您应该创建custom过滤器:

angular.module('app', []).controller('ctrl', function($scope) {
  $scope.searchText = {};
  $scope.items = [
    { id: 1, list: ['abc', 'cde'], name: 'abc' },
    { id: 2, list: ['def', 'abc'], name: 'def' },
    { id: 3, list: ['def', 'ghi'], name: 'ghi' }
  ];
  $scope.visibleItems = $scope.items;
  $scope.FilterArray = function(){    
    function normilize(x){
      return (x + '').toLowerCase();
    }  
    $scope.visibleItems = $scope.items.filter(function(x) {                      
      for(var prop in $scope.searchText){
        var searchVal = normilize($scope.searchText[prop]);
        if(Array.isArray(x[prop])) {
          if(!x[prop].some(x => normilize(x).indexOf(searchVal) != -1))
            return false;
        }
        else{
          var originVal = normilize(x[prop]);                        
          if(originVal.indexOf(searchVal) === -1)
            return false;
        }                                
      }
      return true;
    })
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js">
</script>

<div ng-app='app' ng-controller='ctrl'>
  list: <input type='text' ng-model='searchText.list'/>  
  name: <input type='text' ng-model='searchText.name'/>
  <button ng-click='FilterArray()'>Apply filters</button>
  <ul >  
    <li ng-repeat="item in visibleItems">
      {{item}}
    </li>
  </ul>
</div>


推荐阅读