angularjsng-filter

How to filter a list in angular js by sublevels of object


I received a list of objects from server in something like this

[
    {id: 'a', checked :true,test:{sub:{var:4}}}, 
    {id: 'b', checked:true,test:{sub:{var:3}}},
    {id: 'c', checked:true,test:{sub:{var:2}}},
    {id: 'd', checked:true,test:{sub:{var:2}}},
    {id: 'e', checked:true,test:{sub:{var:3}}}
]

Now I want to want to filter this list on the basis of "var". I am doing something like:

    <div ng-controller="repeatCtrl">
   <div ng:repeat="o in list | filter: {test.sub.var : myPrecious.id}">
       {{o.id}}: 
       <input type="checkbox" ng:model="o.checked" />
       {{o.checked}}
    </div>
</div>

my controller code is like

    var myApp = angular.module('myApp',[]);

myApp.controller('repeatCtrl', function($scope) {
    $scope.list = [
        {id: 'a', checked :true,test:{sub:{var:4}}}, 
        {id: 'b', checked:true,test:{sub:{var:3}}},
        {id: 'c', checked:true,test:{sub:{var:2}}},
        {id: 'd', checked:true,test:{sub:{var:2}}},
        {id: 'e', checked:true,test:{sub:{var:3}}}
    ];

    $scope.myPrecious = 2;
});

What's wrong?


Solution

  • Try this solution. You can just specify {$ : myPrecious.id} at filter without worrying about hierarchy level, as said at docs.angularjs.org: special property name ($ by default) can be used (e.g. as in {$: "text"}) to accept a match against any property of the object or its nested object properties:

    HTML:

    <div ng-repeat="o in list | filter : {$ : myPrecious.id}">
        {{o.id}}
        <input type="checkbox" ng-model="o.checked" />
        {{o.checked}}
    </div>
    

    Javascript:

    $scope.list = [
        {id: 'a', checked:true,test:{sub:{var:4}}}, 
        {id: 'b', checked:true,test:{sub:{var:3}}},
        {id: 'c', checked:true,test:{sub:{var:2}}},
        {id: 'd', checked:true,test:{sub:{var:2}}},
        {id: 'e', checked:true,test:{sub:{var:3}}}
    ];
    
    $scope.myPrecious = {id:2};