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

后端 未结 3 1847
独厮守ぢ
独厮守ぢ 2020-12-31 08:29

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(\"sha         


        
3条回答
  •  有刺的猬
    2020-12-31 08:50

    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"

提交回复
热议问题