1

im using Angular ng-repeat to display $scope.currentMessageList array

i also have a remove button bound via ng-click to the remove function, which looks like this:

remove: function () {
    for (var i = 0; i < 25; i++) {
        var index = i;
        $scope.currentMessageList.splice(index, 1);
        console.log($scope.currentMessageList.length + 'left');
    }
}

There are 25 items in this collection, when I call the remove function, I get this output:

 24left
 23left
 22left
 21left
 20left
 19left
 18left
 17left
 16left
 15left
 14left
 13left
13times X 12left

If I replace the for loop with angular.forEach I get "12 left" only once, still it doesn`t remove more than 13 items

Ive also tried to use angular.apply, than I get digest already in progress error

Deblaton Jean-Philippe
  • 11,188
  • 3
  • 49
  • 66
inlines88
  • 13
  • 3

5 Answers5

0

You're removing items while walking the array.

When you reach half of the array you've already removed half the items, so you won't remove anything else.

You can fix this either by always removing the first item or by iterating backwards from 24 towards 0.

Miguel Ventura
  • 10,344
  • 2
  • 31
  • 41
0

When you remove array items in loop, indexes get shifted too. As the result you can iterate over only the half of them. This is the issue here.

If you want to clear 25 first items you can remove them with Array.prototype.shift method instead. In this case it will remove the first element of the array 25 times, giving you expected result:

remove: function () {
    for (var i = 0; i < 25; i++) {
        currentMessageList.shift();
    }
}
dfsq
  • 191,768
  • 25
  • 236
  • 258
0

Performing a splice while iterating through an array is a bad idea.

You should replace

            for( var i = 0; i < 25; i++ ){
                var index = i;

                $scope.currentMessageList.splice( index, 1 );
                console.log($scope.currentMessageList.length + 'left');                     
            }

by a simple

$scope.currentMessageList.splice( 0, 25 );

Deblaton Jean-Philippe
  • 11,188
  • 3
  • 49
  • 66
0

You don't need to iterate over your array to remove all the items. Just do this:

remove : function(){
                $scope.currentMessageList = [];                 
        }

Check out this answer also. There are others way to achieve this that are also valid.

Community
  • 1
  • 1
nweg
  • 2,825
  • 3
  • 22
  • 30
0

When you splice the array.. the length of the array changes. When you are trying to remove the element at index 13, the length is 12 only. Hence it is not removed. Instead of splice, try shift();

Vinay K
  • 5,562
  • 1
  • 18
  • 27