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
I updated the code . Now angular.extends works as you expected. Remember that if you pass angular.extends an empty object as first parameter (destination) and then the source, angular is going to preserve both objects and copy only the properties, just like angular.copy does.
// angular.copy()
var mySource = {'name' : 'sakshi', 'age' : '24', 'obj' :{'key':'value'}}
var myDest = angular.copy(mySource);
mySource.name = "Beta";
console.log(mySource); // Object {name: "Beta", age: "24", obj: Object}
console.log(myDest); // Object {name: "sakshi", age: "24", obj: Object}
console.log(mySource.obj === myDest.obj); // false
// angular.extend()
var mySource = {'name' : 'sakshi', 'age' : '24', 'obj' :{'key':'value'}}
var myDest = angular.extend(mySource);
mySource.name = "Beta";
console.log(mySource); // Object {name: "Beta", age: "24", obj: Object}
console.log(myDest); // Object {name: "Beta", age: "24", obj: Object}
console.log(mySource.obj === myDest.obj); // True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With