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.

No comments:

Post a Comment