14

I have following html code

  <ul ng-repeat="friend in friends | filter: { age: '2' } | orderBy: 'name' ">
   <li>{{friend.name}}</li>
  </ul>

Here is my $scope variable

 $scope.friends = [
{ name: "Peter",   age: 2 },
{ name: "Pablo",   age: 55 },
{ name: "Linda",   age: 20 },
{ name: "Marta",   age: 37 },
{ name: "Othello", age: 20 },
{ name: "Markus",  age: 32 }
];

It returns

Linda
Markus
Othello
Peter

How the comparison work in ng filter and How do i get friend having age 2 only

Peter
m59
  • 43,214
  • 14
  • 119
  • 136
Muzafar Khan
  • 826
  • 3
  • 15
  • 28
  • In order to have an exact match for your filter you will have to write down a custom filter.Refer to this question http://stackoverflow.com/questions/17480526/angularjs-filter-exact-match – Yameen Feb 24 '15 at 05:53

2 Answers2

24

As of Angular 1.2, you just need to add the strict parameter (true) to the filter so that it looks for an exact match, and pass 2 as a number instead of a string: filter:{age:2}:true

angular.module('myApp', [])
.controller('myCtrl', function($scope) {
   $scope.friends = [
    {name: "Peter",   age: 2 },
    {name: "Pablo",   age: 55},
    {name: "Linda",   age: 20},
    {name: "Marta",   age: 37},
    {name: "Othello", age: 20},
    {name: "Markus",  age: 32}
  ]; 
})
;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp" ng-controller="myCtrl">
  <ul ng-repeat="friend in friends | filter:{age:2}:true | orderBy: 'name' ">
   <li>{{friend.name}}</li>
  </ul>
</body>
m59
  • 43,214
  • 14
  • 119
  • 136
1

Added directive to convert the model value to number workded for me after setting strict parameter (true).

myApp.directive('convertNumber', [function() {
  return {
    require: 'ngModel',
    link: function(scope, el, attr, ctrl) {
      ctrl.$parsers.push(function(value) {
        return parseInt(value, 10);
      });

      ctrl.$formatters.push(function(value) {
        if (value != null) {
          return value.toString();
        };
      });      
    }
  }
}]);
Shahid Chaudhary
  • 890
  • 3
  • 14
  • 25