为什么以及何时使用angular.copy?(深度复制)

我一直在将从服务接收的所有数据直接保存到局部变量、控制器或作用域。我想什么会被认为是一个浅层的副本,这是正确的吗?

Example:

DataService.callFunction()
.then(function(response) {
  $scope.example = response.data;
});

最近,我被告知使用angular.copy来创建深度副本。

$scope.example = angular.copy(response.data);

但是,当我的Angular应用程序使用时,深度复制信息似乎以相同的方式工作。使用深度副本(angular.copy)是否有具体的好处,您能向我解释一下吗?


答案 1

将对象或数组的值分配给另一个变量并且不应更改该对象值时,请使用 angular.copy

如果不使用深度复制或使用 angular.copy,更改属性值或添加任何新属性将更新引用同一对象的所有对象。

var app = angular.module('copyExample', []);
app.controller('ExampleController', ['$scope',
  function($scope) {
    $scope.printToConsole = function() {
      $scope.main = {
        first: 'first',
        second: 'second'
      };

      $scope.child = angular.copy($scope.main);
      console.log('Main object :');
      console.log($scope.main);
      console.log('Child object with angular.copy :');
      console.log($scope.child);

      $scope.child.first = 'last';
      console.log('New Child object :')
      console.log($scope.child);
      console.log('Main object after child change and using angular.copy :');
      console.log($scope.main);
      console.log('Assing main object without copy and updating child');

      $scope.child = $scope.main;
      $scope.child.first = 'last';
      console.log('Main object after update:');
      console.log($scope.main);
      console.log('Child object after update:');
      console.log($scope.child);
    }
  }
]);

// Basic object assigning example

var main = {
  first: 'first',
  second: 'second'
};
var one = main; // same as main
var two = main; // same as main

console.log('main :' + JSON.stringify(main)); // All object are same
console.log('one :' + JSON.stringify(one)); // All object are same
console.log('two :' + JSON.stringify(two)); // All object are same

two = {
  three: 'three'
}; // two changed but one and main remains same
console.log('main :' + JSON.stringify(main)); // one and main are same
console.log('one :' + JSON.stringify(one)); // one and main are same
console.log('two :' + JSON.stringify(two)); // two is changed

two = main; // same as main

two.first = 'last'; // change value of object's property so changed value of all object property 

console.log('main :' + JSON.stringify(main)); // All object are same with new value
console.log('one :' + JSON.stringify(one)); // All object are same with new value
console.log('two :' + JSON.stringify(two)); // All object are same with new value
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="copyExample" ng-controller="ExampleController">
  <button ng-click='printToConsole()'>Explain</button>
</div>

答案 2

在这种情况下,您不需要使用angular.copy()

说明

  • =表示引用,而创建新对象作为深层副本。angular.copy()

  • 使用将意味着更改 的属性将更改 的相应属性,反之亦然。=response.data$scope.example

  • 使用这两个对象将保持独立,并且更改不会相互反映。angular.copy()