I have a ng-repeat
that repeats an unordered list. Each item in that list has a button that calls an AngularJS function to add that item to another list. The problem is that the item that is passed to the function is by reference. Meaning, if I update a property in that function, then the object is updated everywhere in my site.
Example of my problem: /
You'll see that the left list is also updated. But I only want to update the object that is passed to the function! So, I only want to see the changed in the 2nd list.
How can I solve this issue?
I have a ng-repeat
that repeats an unordered list. Each item in that list has a button that calls an AngularJS function to add that item to another list. The problem is that the item that is passed to the function is by reference. Meaning, if I update a property in that function, then the object is updated everywhere in my site.
Example of my problem: http://jsfiddle/XyUGE/156/
You'll see that the left list is also updated. But I only want to update the object that is passed to the function! So, I only want to see the changed in the 2nd list.
How can I solve this issue?
Share Improve this question asked May 17, 2015 at 15:25 VivendiVivendi 21.1k28 gold badges134 silver badges205 bronze badges2 Answers
Reset to default 10In JavaScript, everything is passed by value. You are just modifying the object that the reference points at.
You could use angular.copy
to create a new object with the top level references copied.
I added
obj = angular.copy(obj);
http://jsfiddle/XyUGE/157/
Native method (ONLY Objects, subfunctions copied as well)
var obj = { a : 1, b : 'str', c : function(){ return true; }};
// Deep
var newObject = Object.create(obj);
Brutal method (no functions, not cyclic)
// Deep
var newObject = JSON.parse(JSON.stringify(obj));
Angular method
var newObject = angular.copy(obj);
// or
angular.copy(obj, newObject);
Jquery method
// Shallow copy
var newObject = jQuery.extend({}, obj);
// Deep copy
var newObject = jQuery.extend(true, {}, obj);
Underscore method
// Shallow
var newObject = _.clone(obj);
lodash method
// Deep
var newObject = _.clone(obj, true);