0

I'm trying to delete an element in Angular but i'm getting an Error: [ngRepeat:dupes] after delete an element from list.

My controller:

app.controller("ListController",[function () {
    this.tasks = [
      { id: 1, taskName : "Cras justo odio 1", badge : 10 },
      { id: 2, taskName : "Cras justo odio 2", badge : 12 },
      { id: 3, taskName : "Cras justo odio 3", badge : 14 },
      { id: 4, taskName : "Cras justo odio 4", badge : 15 }
    ];

    this.remove = function(id) {
        var key;
        for (key in this.tasks) {
          if(this.tasks[key].id === id) {
            var found = true;
            break;
          }
        }

        if(found) delete this.tasks[key];
    }
}]);

My view:

  <li class="list-group-item" ng-repeat="task in ListCtrl.tasks">
     <span class="badge">{{task.badge}}</span>
     <button type="button" class="btn btn-xs btn-danger" ng-click="ListCtrl.remove(task.id)"><i class="glyphicon glyphicon-remove"></i></button>
     {{task.taskName}}
  </li>

the stack:

 Error: [ngRepeat:dupes] http://errors.angularjs.org/1.3.13/ngRepeat/dupes?p0=task%20in%20ListCtrl.tasks&p1=undefined%3Aundefined&p2=undefined
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:6:417
at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:233:39
at Object.fn (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:122:63)
at l.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:123:138)
at l.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:126:58)
at HTMLButtonElement.<anonymous> (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:215:36)
at HTMLButtonElement.c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:32:389)
nanndoj
  • 5,650
  • 6
  • 26
  • 39

3 Answers3

2

ng-repeat uses an incremental counter to enumerate arrays. By removing a key in the middle of your array, angular will consider that element undefined. One will not be a problem, but two will cause duplicates (you can't have two elements with the same value in ng-repeat) - the duplicates being two undefined values.

Removing the object with Array.splice() is the correct solution.

using track by $index will solve the duplication error, but you'll end up with empty elements in your html.

Here is a link to the github issue in angular that discusses this situation in depth. The angular team has decided to leave it "as is".

Here is a link to how to remove a specific element from an array with Array.splice().

Community
  • 1
  • 1
Joe Enzminger
  • 10,742
  • 2
  • 45
  • 74
1

use Array.splice(index, count) to remove elements from an array as task is an array of objects

Raulucco
  • 3,268
  • 1
  • 18
  • 26
0

use trackby index in ng-repeat

ng-repeat="task in ListCtrl.tasks track by $index"
A.B
  • 17,478
  • 3
  • 28
  • 54