AngularJS : How to create a two-way data binding between two isolated controllers and a shared service?

你离开我真会死。 提交于 2019-11-30 08:50:51

Fixed it. References will be lost if you are using primitives, as in your fiddle.

Check this:

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

Yet another fun bit: In this case, you don't need to inject $scope or $rootScope. The following code works if you utilize Controller As. Check the Fiddle

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

For even more fun, consider controllers, services, and factories as classes. More Fiddles

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

I've been playing at implementing Josh Carroll's Guidelines to Avoid "Scope Soup"

JavaScript passes objects by reference, so all scopes will point to the same object. Why not just do this?

app.factory("sharedData", function() {
    return {data: "init text from factory"};
});

app.controller("first", function($scope, sharedData) {
    $scope.sharedData = sharedData;
});

app.controller("second", function($scope, sharedData) {
    $scope.sharedData = sharedData;
});

and in your view:

<p>{{sharedData.data}}</p>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!