What is the benefit of angular.copy?

2020-07-18 11:38发布

I use angular.copy in some cases, like copying model default values to the form model, like this:

var customerModel = {
  name: '',
  point: 0
};

$scope.customer = angular.copy(customerModel);

function save() {
  //... Reset $scope.customer after success submit
  $scope.customer = angular.copy(customerModel);
}

... to prevent the default customerModel changed.

But why copy empty object or array? {} or []

I found in some codes used angular.copy on empty object or array. Why they don't assign empty object directly to the variable?

$scope.customer = {}; // or [] for array

If you use copy on empty object or array, could you explain the benefit?

What about ajax response ($http)?

And one more question, what did you do to ajax response? copy or assign it directly to a variable?

$http
  .get('example.com/api/v1/get/customer/1')
  .success(function(response) {
    $scope.customer = angular.copy(response.data);
    // or do you use $scope.customer = response.data ?
  })
;

And if you used copy, what do you think happened to the response object? Is it remain in the memory? or deleted automatically?

2条回答
放荡不羁爱自由
2楼-- · 2020-07-18 11:55

You copy an object to prevent other code from modifying it. (original object might change, but your copy won't see the changes)

If you were to do this:

 $scope.customer = customerModel

... and some callback/service/whatnot changed customerModel, your scope would reflect this change. This is not always desirable, hence the need for deep copying.

Copying empty literal object

$scope.customer = angular.copy({})
// or
$scope.customer = {}

This doesn't make any difference. It's a new empty object every time. Note that it's very different from this:

this.customerModel = {};
$scope.customer = angular.copy(this.customerModel)

Copying ajax response data

Same rules apply. If you want to ensure that this object doesn't change from underneath you (which may happen if you also passed it to somewhere else, for example), you should copy it.

查看更多
趁早两清
3楼-- · 2020-07-18 12:06

angular.copy creates deep copy of variable so that it would hold the reference of another variable

sometimes it happens when user dont want to use call by reference then deep copy comes in action According to your question

var customerModel = {
  name: '',
  point: 0
};

If you will use $scope.customer = angular.copy(customerModel); it will create deep copy of customerModel

As far as $http Service is concerned .Data is coming from response and If you you will assign It directly then there would be no effect of call by reference because data is coming from another source. So I would rather assign it directly in case of $http.get()

查看更多
登录 后发表回答