本文介绍了AngularJS:如何在两个独立控制器和共享服务之间创建双向数据绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create a two-way data binding between two isolated controllers and a shared service (which provides another isolated scope):

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 文本 from factory,但稍后,如果我更改任何它们,这些变化并未反映在这三个范围内.

When the application launches, data1 and data2 are correctly updated to the init text from factory, but later, if I change any of them, those changes are not reflected throughout those three scopes.

如何绑定它们?

附言如果有比返回作用域并仍然可以访问事件和观察功能(基本上不用重写它们)更好的方法,请告诉我.:)

P.S. If there's a better way than returning a scope and still having access to event and observing functionalities (without basically re-writing them), let me know. :)

推荐答案

已修复.如果您使用原语,引用将丢失,就像在您的小提琴中一样.

Fixed it. References will be lost if you are using primitives, as in your 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;
});

这篇关于AngularJS:如何在两个独立控制器和共享服务之间创建双向数据绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 21:10