behrooz dalvandi behrooz dalvandi - 6 months ago 8
AngularJS Question

How to create copy of an object that is not connected to the original one

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?

Answer

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);

Fiddle here