beingalex beingalex - 3 months ago 20
AngularJS Question

Error: ngRepeat:dupes Duplicate Key in Repeater (need track by $index)

https://plnkr.co/edit/bpFi5WuojpNO2rh5vF3T?p=preview

See the README in the Plunker for the following explaination:

I would like the "INJECT NEW" button to create a blank input under
the one that was clicked, not at the end.

The reason they are getting added at the end is because of :

<div ng-repeat="problem in problems track by $index">


The
track by $index
is breaking the injection.

If I take out the
track by $index
then I get the error:
https://docs.angularjs.org/error/ngRepeat/dupes?p0=problem%20in%20problems&p1=object:171&p2={%22key%22:null,%22component%22:null,%22$$hashKey%22:%22object:171%22}

How can I have the inject functionality but not get the error?

Answer

Can change the method like below and can get it working :

$scope.addMotFault = function(idx) {
    if ($scope.problems.length > 1) {

        // Now more than one item, we need to 
        // inject the additional one under the clicked item

        // this index + 1
        problemPrototype.key = idx + 1;
        $scope.problems.splice(idx + 1, 0, angular.copy(problemPrototype));


    } else {

        // Only one item, so just push new problem
        // no need to "inject"

        problemPrototype.key = 0;
        $scope.problems.push(angular.copy(problemPrototype));
    }

};

html:

<div ng-repeat="problem in problems" style="border: 1px #ccc solid; margin:5px; padding: 5px">

It would work i believe.

Comments