Reputation: 1955
I am facing something in my javascript code which I call it a bug but I believe it is technically a feature! So I have a json entity, I create a new one and equalize it to the first one. Now, any change that I perform on the second one, will be affected on the original one as well!
Here is the JSfiddle of simple example I have created: https://jsfiddle.net/Lt7aP/2736/
given the code:
$scope.a = {
name: "mike",
age: 10
};
$scope.b = $scope.a;
$scope.b.name = "john";
shouldn't a.name be "mike" and only b.name become "john"? why does it happen to both of them?
Upvotes: 0
Views: 35
Reputation: 4401
This is definitely not a bug. You have assigned to $scope.b
by reference. Since, $scope.b
changes, so will $scope.a
.
You should use angular.copy
for different references.
$scope.b = angular.copy($scope.a);
Upvotes: 4