angular copy

Which one should you use: angular.copy or angular.extend ?


By: Sheldon Fernandes | July 14, 2015

 

As you’d expect, the correct answer to this questions is not between which one to use, but rather which one you need.  And the best person to answer this is the developer himself.

  • angular.copy(source, destination) :  Here we create a full or deep copy of the object. Essentially a new copy of the object is made, there are now two object pointing to two different memory locations which have the same identical data.
  • angular.extend(destination, src1, src2 …) : Here we create a shallow property copy from one or more source objects to a destination object. The destination will contain all the properties from all the sources.

Check out this code snippet to give you a better idea:

var src = {'id' : '420', 'product' : 'Orange Juice'}
var dest = {}
angular.copy(scr, dest);
console.log(dest);
 
//The output would be: {'id' : '420', 'product' : 'Orange Juice'}

 

var src1 = {'id' : '420', 'product' : 'Orange Juice'}
var src2 = {'brand' : 'Tropicana'}
var dest = {}
angular.extend(dest, src1,src2)
console.log(dest);

//The output would be: {'id' : '420', 'product' : 'Orange Juice', 'brand':'Tropicana'}

Now based on your usage, you can choose between angular.copy or angular.extend.  For further reading, check out angular.copy and angular.extend.

This post has been viewed 4,139 times

2 thoughts on “Which one should you use: angular.copy or angular.extend ?

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>