简体   繁体   中英

AngularJS: Databinding and dot-notation

I think I just lost some hours to the dot-notation in AngularJS.

This Plunker demonstrates the problem which still irritates me:

app.controller('MainCtrl', function($scope, ValueService) {
$scope.obj= ValueService.getObject(); // Output: {"string": "New!!!"}
$scope.val = ValueService.getVal(); // Output: "init"
ValueService.setVal();

})
.service('ValueService', function(){
var output= {string: 'init'};

this.setVal = function(val){
output.string = 'New!!!';
};

this.getObject = function(){
return output;
};

this.getVal = function(){
return output.string;
};

return this;
});

I did know that i should use objects when using ng-model (the dot-notation helps resolving reference issues when searching nested scopes). However I was not aware that this applies to a simple case like this as well. I was even more surprised because the reference to my object stays in tact if i use arrays (and modify it with push/splice): another Plunker

Could someone explain why exactly the databinding does not work for the value anymore when i reassign it? Is there a way to actually bind to the value without passing a wrapper-object from the service?

This is because whenever you return an object from a function in Javascript, you are actually returning a reference to an object. In your example

this.getObject = function(){
    return output;
};

the reference to object is returned. And any changes made to this reference will reflect in the actual object and that is why the data binding works for this.

Whereas, when you return a string from a function, you are returning the value, not the reference to the actual string.

this.getVal = function(){
    return output.string;
};

Here you are returning a string when you return output.string which has value "init" . Any modification done to object.string is not going to change the returned string anymore and that is why it the data binding is failing for value .

See this answer for more information.

the function getVal returns the value of output.string AT THAT POINT IN TIME. you then assign this value to your variable $scope.val. so at that point in time output.string is "Init" hence the value of $scope.val is "Init" This will never change, why would it ? This has nothing to do with angularjs 2-way data-binding or dot notation. You simply assign the value "Init" to $scope.val and never change it again, this is a pure javascript-thing going on here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM