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

12,171

Solution 1

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

Example on fiddle: http://jsfiddle.net/wk0k34na/2/

Solution 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.

Solution 3

Or you could use 'track by $index'... And your limitTo would be:

limitTo: $index == 5 (or any value)
Share:
12,171
Yogesh Mangaj
Author by

Yogesh Mangaj

Full stack engineer with 8 years experience working on core logistics problems and building a big data wrangling and analytics SaaS platform from the ground up Diverse experience spanning Engineering craftsmanship (building core backend modules, leading frontend development), Product development (managing requirements, UX reviews) and Team growth (mentorship, hiring &amp; refining development processes)

Updated on July 22, 2022

Comments

  • Yogesh Mangaj
    Yogesh Mangaj almost 2 years

    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.

    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.

    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

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