First let’s take a look at the sample code
<body ng-app="app"> <div ng-controller="CopyController"> <div> data: <input ng-model="user.data" /><br> user.data: {{user.data}} <br> user1.data: {{user1.data}} <br> <button ng-click="changeData1()">change</button> <br> <button ng-click="copy()">copy</button> <br> copyData: {{copyUser.data}} </div> </div> <script src="node_modules/angular/angular.min.js"></script> </body> <script> angular.module('app', []) .controller('CopyController', function ($scope) { // body... $scope.changeData1 = function () { // body... scope.user1=scope.user1= scope.user; $scope.user1.data = 'is changed'; } $scope.copy = function () { // body... scope.copyUser=angular.copy(scope.copyUser=angular.copy( scope.user); } }); </script>
As you can see from the above demonstration, when the copy button is clicked, the value of copyData becomes "this is old data", and the value of user is successfully copied to copyUser.
When the change button is clicked, the values of user1 and user become 'is changed', but the value of copyUser does not change. At this time, when the value is changed in the input input box, the values of user and user1 will change accordingly, indicating that the two are actually the same variable reference. And copyUser has not changed.
angular.copy can cancel the principle of two-way binding
This is related to the fact that objects in JavaScript are reference types.
Value types in JavaScript
In JavaScript, values are divided into two types: primitive values and reference values.
Primitive values: simple data fields stored in the Stack, that is, their values are stored directly at the locations accessed by variables;
Reference values: stored in the heap, that is, The value stored in a variable is a pointer to the memory location where the object is stored.
Objects in JavaScript are reference values, which means that objects pass values by reference.
So in the above code:
The values of objects $scope.user and $scope.user1 both point to the same reference. For Angular, monitoring variable changes is monitoring the address referenced by its object, so when the reference value of the object changes, all objects pointing to it will change accordingly.
So in Angular, two-way binding cannot be released directly through object assignment. So the way to cancel two-way binding is to create a new object and then assign the value of the original object to the new object. Isn't this just a deep copy in JavaScript?
Yes, angular.copy is the deep copy method provided by Angular. Therefore, the object copied through angular.copy can be consistent with the original object value, and does not point to the same reference as the old object, thus realizing the two-way binding of the object variable.