Pascal
Pascal

Reputation: 181

Duplicate identical object

None of the solutions I've found to this question are satisfying to me.

I have a controller that creates, removes and duplicates items. Whenever I duplicate an item they would obviously have the same properties. Yet I want to be able to distinguish and identify them. Also the duplicated item needs to be inserted right after the original item.

There are some really simple solutions I came up with:

  1. Generate a unique key and assign it to the created item.
  2. Have some id-counter that increments itself by one each item a ID has to be assigned (more or less the same as solution 1; probably faster but unnecessarily pollutes the code).
  3. Insert item in array and re-render so it gets a $$hashKey from Angular.

I imagine the first solution would be best practice since I can create a module for this. The second solution would probably be the fastest solution but I dislike the fact I need a counter. The third solution seems not to be a good idea at all since this goes against the principles of Angular.

I don't know if it is of any use but here's a fiddle.

HTML

<div ng-app ng-controller="MyCtrl">
    <div ng-repeat="item in items">
        <p>{{item.id}}</p>
        <input type="submit" ng-click="duplicateItem(item)" value="Duplicate"></input>
        <input type="submit" ng-click="removeItem(item)" value="Remove"></input>
    </div>
</div>

JavaScript:

var myApp = angular.module('myApp', []);

//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});

function MyCtrl($scope) {
    $scope.items = [
        {
            type: 'text',
            id: 'ID_1' },
        {
            type: 'text',
            id: 'ID_2' }
    ];

    $scope.duplicateItem = function(item) {
        $scope.items.push(item);
    };

    $scope.removeItem = function(item) {
        // Removes item
    };   
}

Upvotes: 0

Views: 191

Answers (1)

Aaron
Aaron

Reputation: 24812

Use angular.copy. This will perform a deep copy that will be recognized by angular as a different object.

The problem when you just duplicate the whole object in native javascript is that you also copy the internal id on which angular bases its model<->view mapping.

Here is an updated version of your jsFiddle where you can see it in action.

Upvotes: 1

Related Questions