What is the use of angular.copy?

I use angular.copy in some cases, like copying model defaults to form model, like:

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 clientModel from being changed.

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

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

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

      

If you are using copy on an empty object or array, could you please explain the benefit?

How about ajax response ($ http)?

And one more question: what did you do with the 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? Does it stay in the memory? or removed automatically?

+3


source to share


2 answers


You are copying the object to prevent other code from changing. (the original object may change, but your copy won't see the change)

If you must do this:

 $scope.customer = customerModel

      

... and some callback / service / whatnot changed customerModel

, your coverage will reflect that change. This is not always desirable, so deep copying is required.

Copying an empty literal



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

      

It does not matter. This is a new empty object every time. Note that this is very different from this:

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

      

Copying ajax response data

The same rules apply. If you want this object not to change from under you (which can happen if you also passed it elsewhere, for example), you must copy it.

+4


source


angular.copy creates a deep copy of a variable so that it retains a reference to another variable

sometimes it happens when the user doesn't want to use a call by reference and then a deep copy is done. According to your question

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

      



If you use $scope.customer = angular.copy(customerModel);

it will create a deep copy of customerModel

As for the $ http Service, the message is sent from the response, and if you assign it directly, there will be no call by reference effect, because the data is coming from a different source. So I would rather assign it directly in the case of $ http.get ()

+3


source







All Articles