lucas lucas - 3 months ago 18
AngularJS Question

deep copy does not work, shallow copy works fine

Would anyone know why the deep copy does not work in my case, the shallow copy/assignment works just fine:



vm.category = null;

$http.get("/api/category/" + vm.categoryId)
.then(function (response) {
//does not work
angular.copy(response.data, vm.category);
//works just fine
vm.category = response.data;
}, function (error) {
vm.errorMsg = "There was an error retrieving category data: " + error;
});





This method for deep copy works fine:

vm.category = angular.copy(response.data);


why:

angular.copy(response.data, vm.category);


does not work?

Answer

From the documentation:

angular.copy(source, [destination]);
destination (optional) Destination into which the source is copied. If provided, must be of the same type as source.

In angular.copy(response.data, vm.category); your source seems to be an array or an object, but the destination, vm.category, is neither an array or an object; it's null.

Try initializing vm.category to [] or {} - to match the type of response.data.

Comments