Simran Kaur
Simran Kaur

Reputation: 1101

angular.copy reflects changes in assigned variable

 var democart= angular.copy($rootScope.cart);
 var cartCopy = democart;

Somewhere in my code, I am updating the value of $rootScope.cart.

That leads to change in value of cartCopy as well which I believe should not be the case.

How do I avoid changes in $rootScope.cart to be reflected in cartCopy?

Note: $rootScope.cart is an array of objects.

Upvotes: 1

Views: 66

Answers (1)

Mathew Berg
Mathew Berg

Reputation: 28750

That is not possible, I just did a quick test and it did not happen:

$rootScope.cart = {};
var democart= angular.copy($rootScope.cart);
var cartCopy = democart;

$rootScope.cart.test = 4;

console.log('$rootScope.cart', $rootScope.cart); // { test: 4 }
console.log('cartCopy', cartCopy); // {}
console.log('democart', democart); // {}

Here's a jsFiddle showing this: http://jsfiddle.net/z7g9cz1o/

Upvotes: 1

Related Questions