javascript AngularJS limitTo 过滤对象上的 ngRepeat(像字典一样使用)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25868760/
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
AngularJS limitTo filter for ngRepeat on an object (used like a dictionary)
提问by Yogesh Mangaj
Is it possible to use limitTo
filter on a ngRepeat
directive which is repeating the properties of an Object and not items in an Array.
是否可以对重复对象属性而不是数组中的项目limitTo
的ngRepeat
指令使用过滤器。
I am aware that the official documentation says that the input to limitTo
needs to be an array or a string. But wondering if there's a way to get this to work.
我知道官方文档说输入到limitTo
需要是数组或字符串。但想知道是否有办法让它发挥作用。
Here's a sample code:
这是一个示例代码:
<li ng-repeat="(key, item) in phones_dict |orderBy:'-age'| limitTo:limit_items"></li>
And $scope.phones_dict
is an Object like
并且$scope.phones_dict
是一个像
{
item_1: {name:"John", age: 24},
item_2: {name:"Hyman", age: 23}
}
回答by Micha? Ignaszewski
limitTo works only for strings and arrays, for object use own filter for example:
limitTo 仅适用于字符串和数组,对于对象使用自己的过滤器,例如:
myApp.filter('myLimitTo', [function(){
return function(obj, limit){
var keys = Object.keys(obj);
if(keys.length < 1){
return [];
}
var ret = new Object,
count = 0;
angular.forEach(keys, function(key, arrayIndex){
if(count >= limit){
return false;
}
ret[key] = obj[key];
count++;
});
return ret;
};
}]);
Example on fiddle: http://jsfiddle.net/wk0k34na/2/
小提琴示例:http: //jsfiddle.net/wk0k34na/2/
回答by Cody Braun
Adding
添加
ng-if ="$index < limit"
to the ng-repeat tag did the trick for me, though it's probably not strictly the "right" way to do this.
ng-repeat 标签对我有用,尽管严格来说这可能不是做到这一点的“正确”方式。
回答by Oam Psy
Or you could use 'track by $index'... And your limitTo would be:
或者你可以使用 'track by $index' ......你的 limitTo 将是:
limitTo: $index == 5 (or any value)