Check out this simple jsfiddle I made to demonstrate my question:
Here is the HTML code snippet:
<div ng-controller="MyCtrl">
<div ng-repeat="p in products">
<span ng-click="overwrite(p)">{{ p.id }}: {{ p.name }}</span>
</div>
</div>
And here is the JavaScript code snippet:
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 does not work, nor does angular.copy(prod)
}
}
After setting properties manually, they are bind correctly. However, when overwriting an object, nothing happens. Why is this? And how can I restore an object to its original state?
Let's say I create a backup object using
var productBackup = angular.copy(product)
. Then I make changes to the original product and later decide to cancel those changes by using product = productBackup
. But unfortunately, this method doesn't work! Do I really need to manually reset all the properties like this?
product.id = productBackup.id;
product.name = productBackup.name;
etc...