Reputation: 181
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:
$$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
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