Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit of angular.copy?

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?

like image 266
Kiddo Avatar asked Dec 13 '25 23:12

Kiddo


1 Answers

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.

like image 197
Sergio Tulentsev Avatar answered Dec 15 '25 12:12

Sergio Tulentsev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!