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

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,但是后来,如果我更改其中任何一个,这些更改都不会在这三个范围中反射(reflect)出来。

如何绑定(bind)它们?

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

最佳答案

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

检查一下:

Updated fiddle

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;
});

关于javascript - AngularJS:如何在两个隔离的 Controller 和共享服务之间创建双向数据绑定(bind)?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23756631/

10-09 16:06
查看更多