Ramesh Rajendran
Ramesh Rajendran

Reputation: 38683

What is the difference between angular.copy() and an assignment (=)?

I want to assign some values when a button click event happens via event parameter:

$scope.update = function(context) {
    $scope.master = context;
};

I have assigned user values to $scope.master.

Now i am seeing angular.copy(). So I wrote the code with angular.copy.

$scope.update = function(context) {
    $scope.master = angular.copy(context)
};

Both are doing same, so what is the difference? Please tell me about the difference between angular.copy() and equal(=).

Upvotes: 37

Views: 43993

Answers (5)

Swayam Rout
Swayam Rout

Reputation: 1

In assignment we share the reference of the object. when we use angular.copy we create a new reference point with the same object details.

var user1={name:'hello'};

The object {name:'hello'} has a reference point(let's say 123, which is saved in user1; when we write

var user2=var user1; //reference point of user2 is also 123 
user2.name="world"; //we update the object in 123
console.log(user1.name); //answer is "world" because reference object is updated

In case you don't want to update user1 when you change something in user2 we have to create a copy. we can do it like

var user2=angular.copy(user1);

or

var user2=Object.assign({},user1);

Upvotes: 0

Asher
Asher

Reputation: 403

= represents a reference whereas angular.copy() creates a new object as a deep copy.

Using = would mean that changing a property of contextwould change the corresponding property of $scope.master or vice versa.

Using angular.copy() the two objects would remain seperate and changes would not reflect on each other.

Upvotes: 11

tomaoq
tomaoq

Reputation: 3056

When you manipulate primitive types (like int) in Javascript, = and angular.copy are the same as any assignment results in copying the value of the variable.

When you manipulate objects in Javascript, = assign a reference to the existing object to the variable and angular.copy is copying, that means creating a new object with the same properties and values and assigning the new object's reference to the variable.

Upvotes: 3

Anders R. Bystrup
Anders R. Bystrup

Reputation: 16060

As can be read here angular.copy() performs a deep copy (cf. "clone") of the argument - essentially creating a new object - whereas using the assignment operator = just assigns reference's.

Thus in the latter case, if you we're to change something in $scope.master you would also change context.

Cheers,

Upvotes: 49

Pankaj Parkar
Pankaj Parkar

Reputation: 136154

Simply

angular.copy() is same as .clone() of jquery which create & returns same object copy with dept. (call by value)

= it does assign the value with its reference value(call by reference),

a = b in this a will be b value is assigned to a, but if both a & b are array then changes in a will reflect in b & vice versa.

Upvotes: 2

Related Questions