Les Paul
Les Paul

Reputation: 1278

angularjs ng-repeat: limitTo not limiting object loop

I want to collect past chats with a limit, but this prints out all the chats.

 <div ng-repeat="(key, value) in chats|limitTo:10">
     <a href="" ng-click="ind(key, value);$event.preventDefault()" class="list-group-item">
         <span class="badge">{{value.time}}</span>
         <i class="fa fa-fw fa-calendar"></i> {{value.partner}}
     </a>
</div>

This is the code in the controller.

    $scope.chats = null;
    var chats = {}
    var id = $store.get('doctor_id');
    var d = new Date();

    doctorFactory.getChatRooms(id).then(function(x){
        for (var i in x){
            chats[i] = { partner: x[i] }
        }
        $scope.chats = dateService.doEquation(chats, d);
        console.log($scope.chats);
    }).catch(function(err){
        console.log(err);
    });

console.log($scope.chats) prints out a series of objects:

2016021085524: Object
    clock: "10:15"
    date: "02/10/2016"
    partner: "Magruder_Douglas"
    time: "0 years ago"
2016021085622: Object
    clock: "10:21"
    date: "02/10/2016"
    partner: "Magruder_Douglas"
    time: "0 years ago"

Upvotes: 0

Views: 1238

Answers (2)

harishr
harishr

Reputation: 18055

limit does not work with objects, for that you will need to implement your own custom filter :

app.filter('objLimitTo', [function(){
    return function(obj, limit){
        var keys = Object.keys(obj);
        if(keys.length < 1) return [];

        var ret = new Object();
        var count = 0;
        angular.forEach(keys, function(key, arrayIndex){
            if(count >= limit) return false;
            ret[key] = obj[key];
            count++;
        });
        return ret;
    };
}]);

i had taken this solution from SO only.. though not able to find the original answer link right now...

Upvotes: 2

Nitin Varpe
Nitin Varpe

Reputation: 10694

This solution does work but. REFERENCE

angular.module('app', []).controller('homeCtrl', function($scope) {
    $scope.limit = 3;
    $scope.expand = function(limit) { 
      $scope.limit += limit;
    }
    $scope.chat = [{ 'data' : 'one'},{ 'data' : 'two'},{ 'data' : 'three'},{ 'data' : 'four'},{ 'data' : 'five'},{ 'data' : 'six'},{ 'data' : 'seven'},{ 'data' : 'eight'},{ 'data' : 'nine'},{ 'data' : 'ten'},{ 'data' : 'eleven'},{ 'data' : 'twelve'},{ 'data' : 'thirteen'},{ 'data' : 'fourteen'},{ 'data' : 'fifteen'}];
});

Upvotes: 0

Related Questions