最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Don't pass object by reference in AngularJS function - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 10

In 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);
发布评论

评论列表(0)

  1. 暂无评论