difference between angular.copy & angular.extend

angular.copy will create a deep copy of an object or an array.

We can use this when we want to make sure that whatever changes we made to the new object won’t change the old object.

Purpose: It is useful when you want to maintain old state and new state of any object or an array.

Example:

var obj1 = { name: 'Sam', company: 'Google', technology: {'angular', 'java'} }; 
var obj2 = angular.copy(obj1); 

console.log(obj2); 
// Output: {  name: 'Sam', company: 'Google', technology: {'angular', 'java'}  } 

console.log(obj1 === obj2); 
// Output: false 

console.log(obj1.technology === obj2.technology); 
// Output: false 
// obj2.technology is a copy of obj1.technology. They don't point to the same technology object.

angular.extend:

Extends the destination object destination by copying own enumerable properties from the source object(s) to destination. You can specify multiple sourceobjects. If you want to retain original objects, you can do that by passing an empty object as the target:

angular.extend(destination, source1, source2, ...);

eg.

Use angular.merge if you want to do recursive merge i.e. deep copy. (Since 1.6.5 this function is deprecated instead you can use third party library like lodash’s merge)

Since extend creates a shallow copy of object. This directive is also useful in many cases where you want to change the parent object too.

myApp.controller(‘MyController’, [ $scope’, function($scope) {
    // models can be used as Source objects
    angular.extend($scope, {
        angular4: Four’,
        angular5: Five
    });
    // methods also can be used as Source objects
    angular.extend($scope, {
      // We will call the function as {{ getAngularVersions() }} in HTML
       getAngularVersions: function() { 
            return $scope.angular4 + ,  + $scope.angular5; 
        }
    });
}]);

 

Advertisements

2 comments

  1. Also mention angular.extend here, since extend creates a shallow copy of object. This directive is also useful in many cases where you want to change the parent object too.
    It works the same with a different syntax.

    Angular.copy –
    Here destObj is optional.
    angular.copy(sourceObj, destObj);

    Angular.extend –
    Where here it assigns one or more sources to one destination object.
    angular.extend(destObj, sourceObj1, sourceObj2);

    Cheers guys

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s