Kid collecting filters

I have the following mock object that I am trying to filter:

{  
    "0":{  
        "boy":{  
            "age":"32",
            "name":"Daniel Grey"
        }
     },
     "1":{  
        "boy":{  
            "age":"23",
            "name":"John Doe"
         }
     }
}

      

And then the ng-repeat directive looks like this:

<ul>
    <li ng-repeat="person in people">{{person.boy.name}}<li>
</ul>

      

My question is, how do I filter people by name? I tried:

<input type="text" ng-model="name">
<ul>
    <li ng-repeat="person in people | filter:name">{{person.boy.name}}<li>
</ul>

      

... but nothing happens [ng-model seems to be disconnected from view! ].

Any answer is greatly appreciated!

Thank!

+3


source to share


1 answer


Updated answer to reflect OP's updates

Looking at the fiddle , yours $scope.people

is essentially an array with one large JSON object with multiple nested objects.This is boy

tricky to work with. If you have control over the construction of the JSON object, I suggest converting to an array of multiple JSON objects that might look something like this:

$scope.people = [
    {
        "name":"Daniel Grey",
        "age":"32",
        "gender": "male"
    },
    {
        "name":"John Doe",
        "age":"23",
        "gender": "male"
    }
];

      

Notice how I converted the key boy

to an attribute gender

.

If you really don't have any control over the data structure, you might need to create a custom filter to parse through the nested structure.

Take a look at the fiddle . A few things to watch out for:

  • I need to specify people[0]

    in ng-repeat

    to retrieve one large JSON object in your array.
  • Custom nameFilter

    searches for an attribute only .boy.name

    .


Original Answer

If you want your filter by name to be simple , you will need to specify specific attributes in your directive ng-model

. So in your case it would be

<input type="text" ng-model="search.boy.name">
<ul>
    <li ng-repeat="person in people | filter:search">{{person.boy.name}}<li>
</ul>

      

But first you need to fix your object JSON

.

UPDATE:

Live demo on fiddle . I noticed that the "name only" filter does not work with angular 1.2.1, but it does work with angular 1.2.2.

+1


source







All Articles