Angular - 对嵌套对象进行过滤

时间:2014-12-17 00:30:32

标签: javascript angularjs angular-filters

我有一个JSON对象数组,正在通过搜索进行过滤。在搜索中,我在ng-model的搜索集上有search.$,但它只搜索每个对象的顶部,但我需要搜索嵌套在其中的所有对象对象。在Angular有一个简单的方法吗?

1 个答案:

答案 0 :(得分:1)

可以使用自定义递归过滤器功能(对于文档,请参阅https://docs.angularjs.org/api/ng/filter/filter),以下示例说明了它:

angular.module('deepFilterTestApp', [])

  .filter('deepFilter', function($filter) {
     return function(text) {
       return function (value) {
            var searchTerm = text;
            if (angular.isObject(value)) {
                var found = false;
                angular.forEach(value, function(v,k) {
                    found = found || $filter('deepFilter')(searchTerm)(v);
                });
                return found;

            } else if (angular.isString(value)) {
                if (value.indexOf(searchTerm) !== -1) {
                    return true;
                } else {
                    return false;
                }
            }
        };
     };
  })

  .controller('DeepFilterTestController', function ($scope) {
  
         $scope.myArray = [
            {
                property1: {
                    deepProperty1: "deeepppp 1!!"
                },
                property2: {
                    deepProperty2: "deeep 2!!"
                }
            },
            {
                property1: {
                    deepProperty1: "dooop 1!!"
                },
                property2: {
                    deepProperty2: {
                        evenDeeperProperty1: "deeepest 2!!"
                    }
                }
            }
        ];

        
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="deepFilterTestApp" ng-controller="DeepFilterTestController">
   
  <p>"dooop": {{ myArray | filter : ('dooop'|deepFilter) }}</p>
  <p>"deeep": {{ myArray | filter : ('deeep'|deepFilter) }}</p>
  <p>"deeepppp": {{ myArray | filter : ('deeepppp'|deepFilter) }}</p>
  <p>"deeepest": {{ myArray | filter : ('deeepest'|deepFilter) }}</p>
  
</div>