Search code examples
javascriptangularjsangularjs-ng-repeat

Add cloned element to ng-repeat


I know that in order to be able to add "duplicates" in an ng-repeat you use track by, but this is not working in my case

I have the following ng-repeat directive:

<div class="well" ng-repeat="surveyData in surveyDatas track by $index">

My user might want to add a new SurveyData to that list, and the difference between them might be just one field out of 50, so cloning it would be the ideal solution, so I try to go about it like this:

DOM:

<button class="btn-sm btn-danger margin10" ng-click="cloneSurveyData(surveyData)">Clone Survey Data:</button>

Controller:

$scope.cloneSurveyData = function (surveyData){
     surveyData.id = null;
     $scope.surveyDatas.push(surveyData);
};

But, of course, I get:

Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: surveyData in surveyDatas | orderBy:'id', Duplicate key: object:150

I've tried tracking by id, and creating a variable in the controller and then equalling it to the SurveyData, nothing

Is my only option to create a new variable and equalize all fields?


Solution

  • try to copy the surveyData with angular.copy to a tmp variable and then push it to the array:

    $scope.cloneSurveyData = function (surveyData){
        var temp = angular.copy(surveyData);
        temp.id = null;
        $scope.surveyDatas.push(temp);
    };
    

    Edit:

    As explanation i hope this will help:

    You didn't have a order by inside your example code but you had it in the error text:

    Repeater: surveyData in surveyDatas | orderBy:'id', Duplicate key: object:150

    With your code you only created a reference and pushed it to the array. So the orderBy tried to order two objects with exactly the same object id.