Angular.js – using angular.copy() function

A simple Angular.js example of copying one object and creating a new copy as a different object. (no reference)
<!DOCTYPE html>
<html ng-app="testApp">
<head>

<style>

</style>

    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
    <meta name="description" content="Tizen Angular.js example"/>

    <title>Tizen Angular.js example</title>

    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/>

    <script src="js/jquery-2.1.4.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/angular.min.js"></script>
    <script>

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

        app.controller('AppController', function($scope) {

          var sampleObj = {};
              sampleObj.weight = 60;
              sampleObj.height = 180;
              sampleObj.colors = {};
              sampleObj.colors.r = 100;
              sampleObj.colors.g = 178;
              sampleObj.colors.b = 245;

              $scope.obj = sampleObj;

              $scope.copiedObj = {};

            $scope.changeObjectToJSON = function() {

              angular.copy($scope.obj, $scope.copiedObj);

            }

        });

    </script>
</head>
<body>
  <br><br>
  <div ng-controller="AppController">

    <button ng-mousedown="changeObjectToJSON()">
      Click this button to create a copy of the object
    </button>
    <br>
    NOTE: using angular.copy makes the copy a total different object (not a reference)
    <br><br>
    source object:  {{ obj }}
    <br><br>
    copied object:  {{ copiedObj }}
  </div>
</body>

</html>

Responses

0 Replies