Sunday, January 18, 2015

Copy object in Angular using angular.copy() function

In JavaScript there are many ways to copy object into another object. AngularJS has built in function to copy one object to another object. In this example we will use angular.copy() function to copy object. Here is sample code to do it.

        var myapp = angular.module('myapp', []);

        //Inject both service and Factory into controller
        myapp.controller('myController', function ($scope, $http) {

            var Address1 = new Object();
   = "Sourav";
            Address1.City = "Kolkata";
   = "1234567890";

            var Address2 = angular.copy(Address1);
            $scope.Address1 = Address1;
            $scope.Address2 = Address2


Now we will implement view to reflect the model. Here is implementation of View.

<body ng-app="myapp" ng-controller="myController" ng-init="getDate()">

    <div ng-model="Address1">
        {{}} <br /> {{Address1.City}} <br /> {{}}

    <div ng-model="Address2">
        {{}} <br /> {{Address2.City}} <br /> {{}}

Once we run the application, we will see that the Address2 object has populated as same of Address1 because we have copied it from Address1.

Here is sample output.

1 comment:

  1. Just wish to say your article is as astounding. The clearness in your
    submit is just excellent and i can suppose you’re knowledgeable in this subject.
    Well along with your permission allow me to take hold of your RSS feed to stay up
    to date with drawing close post. Thanks a million and
    please carry on the rewarding work.

    AngularJS Certification Training in Chennai