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

aka*_*kyy 13 javascript angularjs angularjs-scope angularjs-controller

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

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;
});
Run Code Online (Sandbox Code Playgroud)

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

当应用程序启动data1data2正确更新时init text from factory,如果我更改了其中任何一个,那么这些更改不会反映在这三个范围中.

我该如何绑定它们?

PS如果有一个更好的方法,而不是返回一个范围,仍然可以访问事件和观察功能(基本上不重写它们),请告诉我.:)

lin*_*ink 18

固定它.如果你使用原语,就会丢失引用,就像你的小提琴一样.

检查一下:

更新了小提琴

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;
});
Run Code Online (Sandbox Code Playgroud)

  • @stefan,不仅是性能受到打击,而且不断定义新的范围可能会导致一个世界的麻烦.正如我在下面的答案的评论中提到的,子范围将从父范围继承.在控制器内定义控制器会导致父/子关系.如果我没有弄错,即使在视图中定义变量,也会为控制器的父作用域创建子作用域.看看Josh Carroll关于"Scope Soup"的文章http://www.technofattie.com/2014/03/21/five-guidelines-for-avoiding-scope-soup-in-angular.html (2认同)

Owe*_*wen 6

还有一点有趣的是:在这种情况下,您不需要注入$ scope或$ rootScope.如果您使用Controller As,以下代码可以正常工作.检查小提琴

var app = angular.module("app", []);

app.factory("sharedScope", function() {
    var _this = this;
    _this.data = {text: "init text from factory"};
    return _this;
});

app.controller("first", function(sharedScope) {
    var _this = this;
    _this.data1 = sharedScope.data;
});

app.controller("second", function(sharedScope) {
    var _this = this;
    _this.data2 = sharedScope.data;
});
Run Code Online (Sandbox Code Playgroud)

为了获得更多乐趣,请将控制器,服务和工厂视为类. 更多小提琴

var app = angular.module("app", []);

var SharedScope = function(){
    var _this = this;
    _this.data = {text: "init text from factory"};
    return _this;
};

app.factory("sharedScope", SharedScope);

var First = function(sharedScope){
    var _this = this;
    _this.data1 = sharedScope.data;
};

var Second = function(sharedScope){
    var _this = this;
    _this.data2 = sharedScope.data;
};

First.$inject = ['sharedScope'];
Second.$inject = ['sharedScope'];

app.controller("first", First);              
app.controller("second", Second);
Run Code Online (Sandbox Code Playgroud)

我一直在玩Josh Carroll的避免"范围汤"指南