角 - 嵌套对象上的过滤器(Angular - Filter on nested objects)

2019-10-21 10:42发布

我有正在被搜索过滤JSON对象的数组。 在搜索中,我有ng-model上的搜索设置为search.$ ,但它只能通过每个对象的顶部搜索,但我需要搜索嵌套的对象内的所有对象。 有一个简单的办法做到这一点的角?

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



文章来源: Angular - Filter on nested objects