简体   繁体   English

AngularJS limitTo过滤对象上的ngRepeat(像字典一样使用)

[英]AngularJS limitTo filter for ngRepeat on an object (used like a dictionary)

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. 是否可以在ngRepeat指令上使用limitTo过滤器,该指令重复Object的属性而不是Array中的项。

I am aware that the official documentation says that the input to limitTo needs to be an array or a string. 我知道官方文档说limitTo的输入需要是数组或字符串。 But wondering if there's a way to get this to work. 但想知道是否有办法让这个工作。

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:"Jack", age: 23}
}

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/

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标签为我做了伎俩,尽管它可能不是严格的“正确”方式。

或者你可以使用'跟踪$ index'...而你的限制将是:

limitTo: $index == 5 (or any value)

默认limitTo过滤器在1.5.7之后支持类似于数组的对象( 示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM