Angular.js按精确值过滤(严格相等)

时间:2015-02-24 05:45:12

标签: javascript angularjs

我有以下HTML代码

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

这是我的$ 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 }
];

返回

Linda
Markus
Othello
Peter

如何在ng过滤器中进行比较,以及如何让只有2岁的朋友

Peter

2 个答案:

答案 0 :(得分:21)

从Angular 1.2开始,您只需要在过滤器中添加strict参数(true),以便查找完全匹配,并将2作为数字而不是字符串传递:{{1} }

&#13;
&#13;
filter:{age:2}:true
&#13;
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}
  ]; 
})
;
&#13;
&#13;
&#13;

答案 1 :(得分:1)

添加指令,在设置strict参数(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();
        };
      });      
    }
  }
}]);