Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Angular not databind data when an object is copied from another object?

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...
like image 722
Martijn Avatar asked Jun 12 '13 11:06

Martijn


2 Answers

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.

like image 116
Mark Coleman Avatar answered Nov 08 '22 00:11

Mark Coleman


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];
}
like image 3
Amberlamps Avatar answered Nov 07 '22 23:11

Amberlamps