I've created a simple jsfiddle to illustrate my question:
fiddle
Html:
<div ng-controller="MyCtrl">
<div ng-repeat="p in products">
<span ng-click="overwrite(p)">{{ p.id }}: {{ p.name }}</span>
</div>
</div>
Javascript:
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
var products = [{id:1, name:'first'}, {id:2, name:'second'}];
$scope.products = products;
var prod = {id: 3, name:'third'};
$scope.overwrite = function(p){
p.id = 4;
p.name = 'forth';
p = prod; // this doesn't work nor does angular.copy(prod)
}
}
As you can see, when I set the properties by hand, the values are bind. But when I overwrite an object, nothing happens. How is this possible? And what do I have to do when I want to restore an object in it's original state?
Imagine I create a backup object using var productBackup = angular.copy(product)
. Then I make changes to the original product and later I decide to cancel my changes. I want to do this using product = productBackup
. But this doesn't work! In this case, do I need to set all the properties by hand like this?
product.id = productBackup.id;
product.name = productBackup.name;
etc...
If you use angular.copy(source, destination)
you are able to achieve the desiered effect.
updated fiddle
What is happening is that angular is still watching the original p
reference even after you do the assignment. If you use angular.copy()
you are copying the values from prod
to p
which angular is watching correctly.
I asked a similar question but it dealt with this issue in a shared service.
I have never worked with AngularJS before, but I think what is going on here is that your parameter p
is not your simple key/value object but a more complex AngularJS object. By assigning your prod
to it you are overriding it instead of changing specific parts of the object.
Maybe the following code snippet will help you out:
for(var key in prod) {
p[key] = prod[key];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With