AngularJS模型,多个$ scope和双向数据绑定

nic*_*las 5 angularjs

我喜欢AngularJS不需要和模型的特殊语法,但有一种情况我似乎无法理解.请采取以下措施

我的dataService包含了我正在使用的任何数据存储空间:

app.factory('dataService', function() {
    var data = 'Foo Bar';

    return {
        getData: function() {
            return data;
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

我有两个控制器都访问相同的数据:

app.controller('display', function($scope, dataService) {
    $scope.data = dataService.getData();
});

app.controller('editor', function($scope, dataService) {
    $scope.data = dataService.getData();
});
Run Code Online (Sandbox Code Playgroud)

如果我有两个视图,其中一个修改数据,为什么不自动更新?

<div ng-controller="display">
<p>{{data}}</p>
</div>

<div ng-controller="editor">
<input type="text" value="{{data}}"/>
</div>
Run Code Online (Sandbox Code Playgroud)

我理解这是如何在Knockout中工作的,我将被迫使数据成为可挖掘的可观察对象.因此,应用程序的一部分中的任何修改都会触发另一部分的订阅和更新视图.但我不确定如何在Angular中实现它.

有什么建议?

Aru*_*hny 7

我建议将它变为有效的变化很少.

  1. 将数据对象从字符串更改为对象类型
  2. 使用ng-model绑定输入字段

HTML

<div ng-controller="display">
  <p>{{data.message}}</p>
</div>

<div ng-controller="editor">
  <input type="text" ng-model="data.message"/>
</div>
Run Code Online (Sandbox Code Playgroud)

脚本

app.factory('dataService', function() {
    var data = {message: 'Foo Bar'};

    return {
        getData: function() {
            return data;
        }
    };
});
Run Code Online (Sandbox Code Playgroud)

演示:小提琴