ng-filter by输入的字符串标记

时间:2017-08-31 18:13:49

标签: javascript html angularjs angularjs-scope

我有多个输入字段,我目前正在过滤ng-repeat,如此

...
<input class="form-control" type="text" ng-model="itemFilter.id" /> 
<input class="form-control" type="text" ng-model="itemFilter.attr1" /> 
<input class="form-control" type="text" ng-model="itemFilter.attr2" /> 
 ...
<tr ng-repeat="item in $scope.items | filter:itemFilter | orderBy: '-id'  track by $index"> <td>{{item.id}}</td>
</tr>
 ...

如何从每个输入过滤掉令牌?

例如,如果itemFilter.id = "1 2 3"ng-repeat将包含包含1,2或3的ID

1 个答案:

答案 0 :(得分:1)

正如@Andrei所提到的,你必须编写自己的custom filter来实现所需的功能。下面的代码说明了如何创建它以及如何传递参数来执行自定义过滤逻辑。

这里的想法是使用split()为每个对象属性构建一个标记数组,然后使用过滤器数组上的filter()检查项是否满足过滤器:

&#13;
&#13;
(function (angular) {
    'use strict';

    angular.module("demo", [])
        .filter("filterByTokens", function () {
            return function (items, obj) {
                var separator = obj.separator || ' ';
                var keys = Object.keys(obj).filter(function (key) {
                    return key !== 'separator'
                });
                //create filters array
                var filters = keys.map(function (key) {
                    return {
                        key: key,
                        values: (obj[key] || '').split(separator).filter(function (val) {
                            return !!val;
                        })
                    }
                });

                if (!filters.length) return items;

                return items.filter(function (item) {
                    return filters.filter(function (f) {
                        return !f.values || !f.values.length || (f.values.indexOf(item[f.key].toString()) > -1);
                    }).length === filters.length; // we want to check if all filters are satisfied
                });
            };
        })
        .controller('Demo', [function Demo() {
            var vm = this;

            vm.itemFilter = {id:'1 3 5 2 6', name: 'Test5 Test6', separator: ' '};

            vm.items = [
                {id: 1, name: 'Test1'}, {id: 2, name: 'Test2'}, {id: 3, name: 'Test3'},
                {id: 4, name: 'Test4'}, {id: 5, name: 'Test5'}, {id: 6, name: 'Test6'},
            ];
        }]);

})(angular);
&#13;
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<div ng-app="demo" ng-controller="Demo as vm">     
  <hr/>
  <input class="form-control" type="text" ng-model="vm.itemFilter.id" placeholder="itemFilter.ids"/> 
  <input class="form-control" type="text" ng-model="vm.itemFilter.name" placeholder="vm.itemFilter.names"/> 
  <hr/>
  <code>Filter: {{vm.itemFilter}}</code>
  <hr/>
  <div ng-repeat="item in vm.items | filterByTokens:vm.itemFilter | orderBy: '-id'  track by item.id"> 
    <span>
      {{item.id}}
    </span>
    <span>
      {{item.name}}
    </span>
  </div>  
</div>
&#13;
&#13;
&#13;

P.S。:可能不是最高效的解决方案,只是演示如何使用filters实现这一目标。