Search code examples
angularjsangularjs-filter

Angular js filter is not working?


Please see the output and give the reason why is it working like this?? I am trying to use the filter for nested values and filter is giving random output.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="namesCtrl">

<p>Type a letter in the input field:</p>

<ul>
  <li ng-repeat="x in names | filter:x.na.foo=0">
    {{ x.name }} {{x.na.foo}}
  </li>
</ul>

</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [    
        {name :'Jani' , sName : 0, na :{foo : 0} },
        {name :'Carl' , sName : 1 , na :{foo :1}},
        {name :'Margareth' , sName : 0 , na :{foo : 1}},
        {name :'Hege' , sName : 0, na :{foo : 0} },
        {name :'Joe' , sName : 0 , na :{foo : 1}},
        {name :'Gustav' , sName : 1, na :{foo : 0} },
        {name :'Birgit' , sName : 1 , na :{foo : 1}},
        {name :'Mary' , sName : 0 , na :{foo : 0}},
        {name :'Kai' , sName : 0, na :{foo : 1} }
    ];
});
</script>

<p>The list will only consists of names matching the filter.</p>


</body>
</html>

and the output is :

Type a letter in the input field:

Jani 0
Margareth 1
Hege 0
Joe 1
Gustav 0
Mary 0
Kai 1
The list will only consists of names matching the filter.

Solution

  • use the filter like this when you are filtering nested objects

    <li ng-repeat="x in names | filter: {na: {foo: 0}}">

    Demo

    angular.module('myApp', []).controller('namesCtrl', function($scope) {
        $scope.names = [    
            {name :'Jani' , sName : 0, na :{foo : 0} },
            {name :'Carl' , sName : 1 , na :{foo :1}},
            {name :'Margareth' , sName : 0 , na :{foo : 1}},
            {name :'Hege' , sName : 0, na :{foo : 0} },
            {name :'Joe' , sName : 0 , na :{foo : 1}},
            {name :'Gustav' , sName : 1, na :{foo : 0} },
            {name :'Birgit' , sName : 1 , na :{foo : 1}},
            {name :'Mary' , sName : 0 , na :{foo : 0}},
            {name :'Kai' , sName : 0, na :{foo : 1} }
        ];
    });
    <!DOCTYPE html>
    <html>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <body>
    
    <div ng-app="myApp" ng-controller="namesCtrl">
    
    <p>Type a letter in the input field:</p>
    
    <ul>
      <li ng-repeat="x in names | filter: {na: {foo: 0}}">
        {{ x.name }} {{x.na.foo}}
      </li>
    </ul>
    
    </div>
    
     
    
    <p>The list will only consists of names matching the filter.</p>
    
    
    </body>
    </html>