javascript Angular.js 按精确值过滤(严格相等)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28688932/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular.js filter by exact values (strict equality)
提问by Muzafar Khan
I have following html code
我有以下 html 代码
<ul ng-repeat="friend in friends | filter: { age: '2' } | orderBy: 'name' ">
<li>{{friend.name}}</li>
</ul>
Here is my $scope variable
这是我的 $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 }
];
It returns
它返回
Linda
Markus
Othello
Peter
How the comparison work in ng filter and How do i get friend having age 2 only
ng 过滤器中的比较如何工作以及我如何获得只有 2 岁的朋友
Peter
回答by m59
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 1.2 开始,您只需要向过滤器添加严格参数 (true) 以便它查找精确匹配,并2
作为数字而不是字符串传递: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>
回答by Shahid Chaudhary
Added directive to convert the model value to number workded for me after setting strict parameter (true).
添加了在设置严格参数(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();
};
});
}
}
}]);