如何根据Angular js中的两个自定义过滤器过滤数据

Tar*_*ngh 11 javascript angularjs

我有两个自定义过滤器,我想使用这两个自定义过滤器过滤我的数据.但是我遇到了这个问题,如果我一个接一个地使用它们就可以了,但是当我尝试同时使用两个滤波器时却没有输出.我的代码如下:

<script>
     var myApp = angular.module('myApp', []);
     myApp
.filter('selectedTags', function() {
    return function(postdata, tags) {
        return postdata.filter(function(task) {

            for (var i in task.tarn_list) {
                if (tags.indexOf(task.tarn_list[i]) != -1) {
                    return true;
                }
            }
            return false;

        });
    };
})
.filter('selectedDep', function() {
    return function(postdata, tags) {
        return postdata.filter(function(task) {

            for (var i in task.deployment) {
                if (tags.indexOf(task.deployment[i]) != -1) {
                    return true;
                }
            }
            return false;

        });
    };
})
.controller('PostList', ['$scope', '$http', function($scope, $http) {
           var jsonFile='../../json.php';
           $http.get(jsonFile).success(function(data) {
            $scope.postdata = data;
           });
           $scope.useMakes=[]
           $scope.checkBoxModel={
                    search:[],
                    ddsearch:[]
                };
           $scope.totalFeatures=features;
           $scope.deployment=all_deployment;
        }]);
</script>
Run Code Online (Sandbox Code Playgroud)

我的div如下所示我想应用过滤器:

<div ng-repeat="record in postdata | selectedDep:checkBoxModel.ddsearch | selectedTags:checkBoxModel.search" >
Run Code Online (Sandbox Code Playgroud)

小智 3

没有看到实际的数据集,我认为这应该能让船漂浮 - 考虑到您在问题中暴露的属性和循环的性质;

https://jsfiddle.net/op7m14m1/1/


我没有选择for in循环,而是选择了嵌套过滤器(这本质上就是您正在做的事情)。

var predicate = [];

dataset.filter(function (a) {
  var inner = a.inner.filter(function (b) {
    return predicate.indexOf(b) > -1;
  });

  return inner.length > 0; 
});
Run Code Online (Sandbox Code Playgroud)

查看您拥有的两个过滤器,您可以将其分解为一个函数,并使用绑定(或传入)参数来指示将哪个属性用作过滤器的匹配器。

像这样的东西;

function generic () {
  return function (prop, dataset, predicate) {
    return dataset.filter(function (element) {

      var innards = element[prop].filter(function (iEl) {
        return predicate.indexOf(iEl) > -1;
      });

      return innards.length > 0;
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

然后要使用它,您可以执行以下操作;

 module.filter('genericFilter', generic);
 module.filter('selectedDep',   generic.bind(null, 'deployment');
 module.filter('selectedTags',  generic.bind(null, 'tarn_list');

 // $filter('genericFilter')('deployment', [], ['a']);
 // $filter('selectedDep')([], ['b']);
 // $filter('selectedTags')([], ['c']);
Run Code Online (Sandbox Code Playgroud)

此设置允许使用单个函数,您可以根据需要重用该函数 - 只需传入您想要进行深度过滤的属性,或抢先绑定它。