- AngularJS provides copy() and extend() method for object manipulation.
- angular.copy(source,destination) method supports deep copy where destination object elements are deleted and source elements are copied to destination.
- angular.extend(destination,source) method does not support deep copy.Only enumerable object properties are copied from source to destination.
- In this demo, “We have created 2 sets of array and object and used copy and extend method”.
- Below code has 2 flower array fruitArraySource, fruitArrayDestination.fruitArraySource is copied to fruitArrayDestination. elements of fruitArrayDestination is deleted and fruitArraySource is copied on top of it.subjectObjectDestination,studentObjectSource are 2 objects.studentObjectSource enumerable properties are copied to subjectObjectDestination.
<!DOCTYPE html> <html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
<meta charset="utf-8">
<title>AngularJS copy() and extend() method Example</title>
</head>
<body ng-controller="MyController" ng-cloak>
<h1>Angular copy and extend method Example</h1>
<h3>$scope.fruitArrayDestination</h3>
<ol>
<li ng-repeat="item in fruitArrayDestination">
{{item}}
</li>
</ol>
<h3>$scope.subjectObjectDestination with extend()</h3>
{{subjectObjectDestination | json}}
<script>
var myApp = angular.module("myApp", []);
myApp.controller("MyController", ["$scope", function($scope) {
$scope.fruitArraySource = ["Mango", "Apple"];
$scope.fruitArrayDestination = ["Orange", "Grapes"];
angular.copy($scope.fruitArraySource, $scope.fruitArrayDestination);
$scope.studentObjectSource = {
"name": "Sandeep"
};
$scope.subjectObjectDestination = {
"subject": "computer"
};
angular.extend($scope.subjectObjectDestination,
$scope.studentObjectSource);
}]);
</script>
</body>
</html>
- The output of the above code is in below JSBIN link.