$scope.Object1=$scope.Object2 (assigning to reference and not to value). was this there in angular from beginning or is it a new feature ?
-
If you want to clone an object instead, this question may be of use to you: http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object – Dave Feb 18 '16 at 19:05
2 Answers
Issue has absolutely nothing to do with angular. That's how javascript object inheritance works. Objects are always assigned by reference
Easy to see this for yourself
var a = {foo: 1};
var b = a;
b.foo = 2;
alert(a.foo);// 2

- 170,828
- 13
- 121
- 150
What is happening is that the object1 is pointing to the memory reference of the object2, this is not an angular feature, in fact is a behavior of how the variable assignment works in javascript.
Angular includes a helper function to make copies to avoid this case, for example using angular.copy() you can make a copy of the object instead of pointing to the reference.
$scope.object1 = angular.copy($scope.object2);
In that way when the $scope.object2 changes, the changes are not reflected on the $scope.object1 because is not pointing to the object2 reference, object1 is a object copy of the object2 before change so is pointing to a new object reference.
So in javascript:
- Objects are references
- Primitives (numbers, strings etc) are passed by value.
Also you can take a look at: