本文介绍了AngularJS limitTo 过滤对象上的 ngRepeat(像字典一样使用)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 ngRepeat 指令上使用 limitTo 过滤器,该指令重复对象的属性而不是数组中的项目.

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 的输入需要是数组或字符串.但想知道是否有办法让它发挥作用.

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.

这是一个示例代码:

<li ng-repeat="(key, item) in phones_dict |orderBy:'-age'| limitTo:limit_items"></li>

$scope.phones_dict 是一个类似的对象

And $scope.phones_dict is an Object like

{ 
     item_1: {name:"John", age: 24},
     item_2: {name:"Jack", age: 23}
}

推荐答案

limitTo 仅适用于字符串和数组,对于对象使用自己的过滤器例如:

limitTo works only for strings and arrays, for object use own filter for example:

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;
    };
}]);

小提琴示例:http://jsfiddle.net/wk0k34na/2/

这篇关于AngularJS limitTo 过滤对象上的 ngRepeat(像字典一样使用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 08:14