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.

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


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


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

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

        });
     </script>

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">
        {{Address1.name}} <br /> {{Address1.City}} <br /> {{Address1.phone}}
    </div>

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

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

    ReplyDelete