我喜欢 AngularJS 不需要模型的特殊语法,但有一种情况我似乎无法理解。采取以下
我的 dataService 包装了我正在使用的任何类型的数据存储:
app.factory('dataService', function() {
var data = 'Foo Bar';
return {
getData: function() {
return data;
}
};
});
我有两个 Controller 都访问相同的数据:
app.controller('display', function($scope, dataService) {
$scope.data = dataService.getData();
});
app.controller('editor', function($scope, dataService) {
$scope.data = dataService.getData();
});
如果我有两个 View ,其中一个修改数据,为什么另一个不自动更新?
<div ng-controller="display">
<p>{{data}}</p>
</div>
<div ng-controller="editor">
<input type="text" value="{{data}}"/>
</div>
我了解这在诸如 Knockout 之类的东西中是如何工作的,在这种情况下,我将被迫将数据设为可淘汰的可观察对象。因此,对应用程序某一部分的任何修改都会触发订阅并更新另一部分的 View 。但我不确定如何在 Angular 中进行操作。
有什么建议吗?
最佳答案
我建议进行一些更改以使其正常工作。
HTML
<div ng-controller="display">
<p>{{data.message}}</p>
</div>
<div ng-controller="editor">
<input type="text" ng-model="data.message"/>
</div>
脚本
app.factory('dataService', function() {
var data = {message: 'Foo Bar'};
return {
getData: function() {
return data;
}
};
});
演示:Fiddle
关于AngularJS 模型、多个 $scope 和双向数据绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15736912/