admin管理员组文章数量:1356368
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);
本文标签: javascriptDon39t pass object by reference in AngularJS functionStack Overflow
版权声明:本文标题:javascript - Don't pass object by reference in AngularJS function - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744038100a2580151.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论