Objects can be copied in following ways
By default Object variable is copied by reference if directly variable assigned on right side i.e variable2=variable1
Code Example
//user-1 variable with nested object $scope.user1 = { "id": 1, "firstName": "foo", "lastName": "bar", "address": { "city": "city 1", "landmark": "landmark 1", "pincode": "000011", "street": "street 1" } } //create new variable by assigning reference of user-1 $scope.user2 = $scope.user1; //Change city of user-2 $scope.user2.address.city = "New City"; //Change firstName of user-2 | $scope.user2.firstName = "New foo"; //Change firstName of user-2 $scope.user2.id = 5; //Print both variable value console.log("user-1 data", $scope.user1); console.log("user-2 data", $scope.user2);
Output:
Here the value of user 2 has been changed though it’s updated for user 1 as well because the user 2 object is created by reference of user 1.
Code Example
//user-1 variable with nested object $scope.user1 = { "id": 1, "firstName": "foo", "lastName": "bar", "address": { "city": "city 1", "landmark": "landmark 1", "pincode": "000011", "street": "street 1" } } //create new variable by assigning shallow copy of user-1 using angular.extend method $scope.user2 = angular.extend({}, $scope.user1); //Change city of user-2 $scope.user2.address.city = "New City"; //Change firstName of user-2 $scope.user1.firstName = "New foo"; //Change firstName of user-2 $scope.user2.id = 5; //Print both variable value console.log("user-1 data", $scope.user1); console.log("user-2 data", $scope.user2);
Here in output we can see the updated value of user 2 with updated fields firstname and Id,But address is nested object, as a result user 2 address will still refer the user 1 address reference
Hence for both user the city is updated though in code just city of user 2 is updated
Angular.copy Syntax:
> angular.copy(source, [destination]);
Code Example
//user-1 variable with nested object $scope.user1 = { "id": 1, "firstName": "foo", "lastName": "bar", "address": { "city": "city 1", "landmark": "landmark 1", "pincode": "000011", "street": "street 1" } } //crete new variable by assigning deep copy of user-1 using angular.copy method $scope.user2 = angular.copy($scope.user1); //Change city of user-2 $scope.user2.address.city = "New City"; //Change firstName of user-2 $scope.user2.firstName = "New foo"; //Change firstName of user-2 $scope.user2.id = 5; //Print both variable value console.log("user-1 data", $scope.user1); console.log("user-2 data", $scope.user2);
Here as deep copy is performed,Hence any kind of update of user 2 is not reflected to user 1