I have an array of JSON objects that is being filtered by a search. In the search, I have the ng-model on the search set to search.$, but it only searches through the top part of each of the objects, but I need to to search all the objects nested inside of the objects. Is there an easy way to do that in Angular?
-
Could you provide some code for us to analyze ?Sephy– Sephy2014-12-17 07:50:13 +00:00Commented Dec 17, 2014 at 7:50
Add a comment
|
1 Answer
It is possible using a custom recursive filter function (for docs, see https://docs.angularjs.org/api/ng/filter/filter), the following example illustrates it:
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>
4 Comments
m0ngr31
I put up a jsFiddle here: jsfiddle.net/s2262g06 but I get an error trying to use it on a search:
Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!NicBright
I've fixed the issue with your fiddle. See here for a working copy: jsfiddle.net/s2262g06/1
NicBright
As it turns out, Angular was supposed to be able to do this all the time. It hasn't worked since version 1.3.6 but is expected to work again in 1.3.8, see github.com/angular/angular.js/commit/… --- that said: consider the example of this answer as a demo of how you can use a custom filter creating a filter function for the filterFilter
user841760
thanks for sharing this! how would I show entire inheritance for the queried value? Let's say I wanted to search for
deeepest 2!! and it had children deeepest 3!! and deeepest 3!! would have deeepest 4!!, I'd want to see these too?