Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS: angular.copy crashes the browser when an object references another object

I have the following JavaScript/Angular code:

var a = {};
var b = {};
a.ref = b;
b.ref = a;
angular.copy(a);

When angular.copy fires, the browser locks up. I'm assuming this is because the copy function is doing a deep copy, and when it starts to copy a's reference of b, it goes into b and then wants to copy its reference of a, thus creating a circular copy, which will never end.

Is this assumption right? If so, is there a way to avoid this? I'm assuming the answer will involve changing the way my data looks, but I'm curious to hear another person's thoughts.

like image 484
incutonez Avatar asked Oct 22 '22 10:10

incutonez


1 Answers

Your assumption is right, the problem is the circular reference. JSON.stringify will also complain about this structure. jQuery.extend detects circular references at a very basic level and can handle your basic example here, but jQuery.extend has its own issues as well. If you're already using jQuery, you can just use extend, but otherwise you may want to look at writing something yourself, or you can use this fancy cloneObject function I found via Google:

https://gist.github.com/NV/1396086

like image 188
Langdon Avatar answered Oct 27 '22 11:10

Langdon