// declare a module var myApp = this.angular.module('myApp', []); // declare a controller myApp.controller('InputCtrl', function ($scope) { $scope.arr = ['apple', 'banana', 'carrot']; $scope.appStr = JSON.stringify($scope.arr); $scope.arr1 = $scope.arr; $scope.arr1[0] = 'avocado'; //This helps you to clone the Array as a new Array. $scope.arr2 = JSON.parse(JSON.stringify($scope.arr)); $scope.arr2[1] = 'blueberry'; $scope.obj = { name: 'Name', arr: ['apple', 'banana', 'carrot'] }; $scope.objStr = JSON.stringify($scope.obj); $scope.obj1 = $scope.obj; $scope.obj1.name = 'Name1'; $scope.obj1.arr[0] = 'avocado'; //This helps you to clone the Object as a new Object. $scope.obj2 = JSON.parse(JSON.stringify($scope.obj)); $scope.obj2.name = 'Name2'; $scope.obj2.arr[1] = 'blueberry'; });
<!-- stitch this with the module declare in Javascript --> <body ng-app="myApp"> <div ng-controller="InputCtrl"> <table> <tr> <td><b>(For Array)</b></td> </tr> <tr> <td><b>Original value of $scope.app</b></td> </tr> <tr> <td><b>{{appStr}}</b><br/><br/></td> </tr> <tr> <td><b>This causes the original and the copy of array to be affected. (Changing first item of $scope.arr1 to 'avocado')</b></td> </tr> <tr> <td>First item of $scope.app: <b>{{arr[0]}}</b>.</td> </tr> <tr> <td>First item of $scope.arr1: <b>{{arr1[0]}}</b>.<br/><br/></td> </tr> <tr> <td><b>This doesn't affects the original array. (Changing second item of $scope.arr2 to 'blueberry')</b></td> </tr> <tr> <td>Second item of $scope.app: <b>{{arr[1]}}</b>.</td> </tr> <tr> <td>Second item of $scope.arr2: <b>{{arr2[1]}}</b>.<br/><br/></td> </tr> <tr> <td><b>(For Object)</b></td> </tr> <tr> <td><b>Original value of $scope.obj</b></td> </tr> <tr> <td><b>{{objStr}}</b><br/><br/></td> </tr> <tr> <td><b>This causes the original and the copy of object to be affected. (Changing first item of $scope.obj1.arr to 'avocado' and $scope.obj1.name to 'Name1')</b></td> </tr> <tr> <td>Value of $scope.obj.name: <b>{{obj.name}}</b>.</td> </tr> <tr> <td>First item of $scope.obj.arr: <b>{{obj.arr[0]}}</b>.</td> </tr> <tr> <td>Value of $scope.obj1.name: <b>{{obj1.name}}</b>.</td> </tr> <tr> <td>First item of $scope.obj1.arr: <b>{{obj1.arr[0]}}</b>.<br/><br/></td> </tr> <tr> <td><b>This doesn't affects the original object. (Changing second item of $scope.obj2.arr to 'blueberry' and $scope.obj2.name to 'Name2')</b></td> </tr> <tr> <td>Value of $scope.obj.name: <b>{{obj.name}}</b>.</td> </tr> <tr> <td>Second item of $scope.obj.arr: <b>{{obj.arr[1]}}</b>.</td> </tr> <tr> <td>Value of $scope.obj2.name: <b>{{obj2.name}}</b>.</td> </tr> <tr> <td>Second item of $scope.obj2.arr: <b>{{obj2.arr[1]}}</b>.</td> </tr> </table> </div> </body>