Why and when to use angular.copy? (Deep Copy)

2019-01-21 00:02发布

I've been saving all the data received from services direct to local variable, controller, or scope. What I suppose would be considered a shallow copy, is that correct?

Example:

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

Recently I was told to use angular.copy in order to create a deep copy.

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

However, the deep copy information seems to be working in the same way when used by my Angular application. Are there specific benefits to using a deep copy (angular.copy) and can you please explain them to me?

7条回答
Summer. ? 凉城
2楼-- · 2019-01-21 00:33

I would say angular.copy(source); in your situation is unnecessary if later on you do not use is it without a destination angular.copy(source, [destination]);.

If a destination is provided, all of its elements (for arrays) or properties (for objects) are deleted and then all elements/properties from the source are copied to it.

https://docs.angularjs.org/api/ng/function/angular.copy

查看更多
登录 后发表回答