Binding doesn't update when the original object changes

无人久伴 提交于 2019-12-12 14:54:38

问题


I think I have misunderstood something about how data-binding and scopes work in Angular, or maybe I have some misconception in Javascript in general. I hope somebody can help me.

Let's say I have a factory that has an object, and defines a getter/setter for it:

app.factory('myFactory', function(){

    var myObject : {

        subObject : {

             subProperty : 'value'
        }
    };

    return {

        getObject : function() {

            return myObject;
        },

        setObject : function(obj) {

            myObject = obj;
        }
    };
};

Then, in a controller I get this object and assign the subObject to the scope:

app.controller('myController', function($scope, myFactory){

    var myObject = myFactory.getObject();

    $scope.subObject = myObject.subObject;
});

In the view, I bind to the subProperty of that object:

<div> {{subObject.subProperty}} </div>

Then, somebody calls the myFactoy.setObject() method and replaces the original object in the factory for a new one. Shouldn't my binding be updated automatically?? if it shouldn't... which is the best way to accomplish this??


回答1:


The original object doesn't change. You're just changing the reference to it.


Use this instead:

setObject : function(obj) {

    angular.copy(obj, myObject);
}


来源:https://stackoverflow.com/questions/24519698/binding-doesnt-update-when-the-original-object-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!