behrooz dalvandi behrooz dalvandi - 2 years ago 77
AngularJS Question

How to create copy a json entity 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?

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download