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.

No comments:

Post a Comment