behrooz dalvandi behrooz dalvandi - 9 months ago 25
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:

given the code:

$scope.a = {
name: "mike",
age: 10

$scope.b = $scope.a;

$ = "john";

shouldn't be "mike" and only become "john"? why does it happen to both of them?


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