小编典典

AngularJS:如何在两个隔离的控制器和共享服务之间创建双向数据绑定?

angularjs

我正在尝试在两个隔离的控制器和一个共享服务(提供另一个隔离范围)之间创建双向数据绑定:

app.factory("sharedScope", function($rootScope) {
    var scope = $rootScope.$new(true);
    scope.data = "init text from factory";
    return scope;
});

app.controller("first", function($scope, sharedScope) {
    $scope.data1 = sharedScope.data;
});

app.controller("second", function($scope, sharedScope) {
    $scope.data2 = sharedScope.data;
});

小提琴:http :
//jsfiddle.net/akashivskyy/MLuJA/

当应用程序启动data1data2正确更新到时init text from factory,但是以后,如果我更改其中任何一个,这些更改都不会在这三个范围中反映出来。

如何绑定它们?

PS:如果有比返回范围更好的方法,并且仍然可以访问事件并观察功能(基本上无需重写它们),请告诉我。:)


阅读 213

收藏
2020-07-04

共1个答案

小编典典

解决它。如果您使用的是图元,则引用将丢失。

检查一下:

更新的小提琴

app.factory("sharedScope", function($rootScope) {
    var scope = $rootScope.$new(true);
    scope.data = {text: "init text from factory"};
    return scope;
});

app.controller("first", function($scope, sharedScope) {
    $scope.data1 = sharedScope.data;
});

app.controller("second", function($scope, sharedScope) {
    $scope.data2 = sharedScope.data;
});
2020-07-04