Explanation :
we come across some situation in which we need to copy one object to another object. In that case, we probably have two solutions: angular.copy() or angular.extend().
Challenge i am facing :
As we know angular.copy(source, destination)
creates a deep copy of source object and assign it to destination. By writing deep copy, we mean that a new copy of the referred object is made and its working fine.
deep copy code :
var mySource = {'name' : 'Beta', 'age' : '24'}
var myDest = {}
angular.copy(mySource,myDest);
mySource.name = "Alpha";
console.log(mySource); // Object {name: "Alpha", age: "24"}
console.log(myDest); // Object {name: "Beta", age: "24"}
console.log(mySource.obj === myDest.obj); // false
Here, I modify the source object mySource.name = "Alpha"
but it is not affecting the destination object myDest
as expected.
If we check mySource.obj === myDest.obj
, this will give false because both point to different objects.
Now,I am facing issue with angular.extend(destination, source)
as it creates a shallow copy
means in this both source and destination will point to same address. So, if i will modify source object then it will also reflect in destination object. But it's not happening.
shallow copy code :
var mySource = {'name' : 'Beta', 'age' : '24'}
var myDest = {}
angular.extend(myDest,mySource);
mySource.name = "Alpha";
console.log(mySource); // Object {name: "Alpha", age: "24"}
console.log(myDest); // Object {name: "Beta", age: "24"}
console.log(mySource.obj === myDest.obj); // True
jsfiddle : https://jsfiddle.net/U3pVM/24322/
As i am new in this, need help to understand the proper flow of angular.copy() & angular.extend().
Any immediate help will be highly appreciable. Thanks
angular.extend
uses the same references for the inner objects), and your summary states the other thing. – Felspar