如何在Angular js中基于两个自定义过滤器过滤数据

How to filter data based on two custom filters in Angular js

本文关键字:自定义 于两个 过滤器 过滤 数据 Angular js      更新时间:2023-09-26

我有两个自定义筛选器,我想用这两个自定义过滤器过滤我的数据。但我面临的问题是,如果我一个接一个地使用,那么它们效果很好,但当我试图同时使用两个过滤器时,就没有输出了。我的代码如下:

<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>

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

<div ng-repeat="record in postdata | selectedDep:checkBoxModel.ddsearch | selectedTags:checkBoxModel.search" >

在没有看到实际数据集的情况下,考虑到你在问题中暴露的属性和循环的性质,这里的应该让船漂浮起来;

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; 
});

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

像这样的东西;

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;
    });
  }
}

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

 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']);

此设置允许使用一个函数,您可以随心所欲地重复使用该函数-只需传入要对其进行深度筛选的属性,或抢先绑定它。