问题
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