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?
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:
... 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
This doesn't make any difference. It's a new empty object every time. Note that it's very different from this:
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.
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
If you will use
$scope.customer = angular.copy(customerModel);
it will create deep copy of customerModelAs 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()