我正在尝试在两个独立 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;
});
fiddle :http://jsfiddle.net/akashivskyy/MLuJA/
当应用程序启动时,data1 和 data2 正确更新为 init text from factory,但稍后,如果我更改任何他们,这些变化并没有反射(reflect)在这三个范围内。
如何绑定(bind)它们?
附言如果有比返回一个范围并且仍然可以访问事件和观察功能(基本上不需要重写它们)更好的方法,请告诉我。 :)
最佳答案
修复它。如果您使用基元,引用将会丢失,就像您的 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 - Angular : How to create a two-way data binding between two isolated controllers and a shared service?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23756631/