AngularJS models, multiple $scopes, and two-way data binding
angularjs
Solution
There are few changes that I would suggest to make it work.
- change the data object from a string to object type
- Use ng-model to bind the input field
HTML
<div ng-controller="display">
<p>{{data.message}}</p>
</div>
<div ng-controller="editor">
<input type="text" ng-model="data.message"/>
</div>
Script
app.factory('dataService', function() {
var data = {message: 'Foo Bar'};
return {
getData: function() {
return data;
}
};
});
Demo: Fiddle
Problem
I like that AngularJS doesn't require and special syntax for Models, but there's one scenario I can't seem to wrap my head around. Take the following My dataService wraps whatever flavor of data storage I'm using: ``` app.factory('dataService', function() { var data = 'Foo Bar'; return { getData: function() { return data; } }; }); ``` I have two controllers that both access the same piece of data: ``` app.controller('display', function($scope, dataService) { $scope.data = dataService.getData(); }); app.controller('editor', function($scope, dataService) { $scope.data = dataService.getData(); }); ``` If I then have two views, one of which modifies the data, why doesn't the other update automatically? ``` <div ng-controller="display"> <p>{{data}}</p> </div> <div ng-controller="editor"> <input type="text" value="{{data}}"/> </div> ``` I understand how this is working in something like Knockout where I'd be forced to make the data a knockout observable object. So any modifications in one part of the application trigger subscriptions and update views in another. But I'm not sure how to go about it in Angular. Any advice?