Can ng-repeat limitTo be applied to repeat on json instead of array?

I am doing ng-repeat on a json object based on its keys. Now I can limit the number of repeated items to 5 using ng-repeat = "item in array | limitTo: 5" on the array object.

But when I try to do ng-repeat = "key in json | limitTo: 5" it doesn't underestimate the number of repetitions, what should I do?

+3


source to share


2 answers


Create a custom filter to handle the json object:



app.filter('limitTo', function () {
    return function (jsonItems, limit) {
        var lengthJson = Object.keys(jsonItems).length;
        if (lengthJson<=limit)
            return jsonItems;
        else
        {
            var slicedJsonItems = {};

            //your slicing algorithm here to limit the length

            return slicedJsonItems;
        }
    };
});

      

+1


source


As you can see from the documentation:

https://docs.angularjs.org/api/ng/filter/limitTo

The input is limited to: The original array, string or number, which must be limited.



You can create your own filter to do this limitation.

For more information see: AngularJS limitTo filter for ngRepeat on object (used as dictionary)

Also, what is the reason for using a limitTo filter on an object when you cannot control the order? Array would be better here.

+1


source







All Articles