Skip to content Skip to sidebar Skip to footer

Angular - Filter On Nested Objects

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 e

Solution 1:

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) {
     returnfunction(text) {
       returnfunction (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;

            } elseif (angular.isString(value)) {
                if (value.indexOf(searchTerm) !== -1) {
                    returntrue;
                } else {
                    returnfalse;
                }
            }
        };
     };
  })

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

        
  });
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><divng-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>

Post a Comment for "Angular - Filter On Nested Objects"