简体   繁体   English

如何在 AngularJS 中的两个独立模块之间共享数据

[英]How to share data between two separate modules in AngularJS

I need to know how to sync data between two controllers in different modules.我需要知道如何在不同模块中的两个控制器之间同步数据。 below is the code I'm using.下面是我正在使用的代码。 I tried to use the service with the observer pattern.我尝试将服务与观察者模式一起使用。 but it seems that the service instance injected on the two apps are quite different但是好像两个app上注入的服务实例差别很大

angular.module('app3', []).service('sharedService', function () {
        this.Country = 'USA';
        this.scope = null;
        this. observerCallbacks = [];

        //register an observer
        this.registerObserverCallback = function (callback) {
            this.observerCallbacks.push(callback);
        };

        //call this when you know 'foo' has been changed
        this.notifyObservers = function () {
            alert('notifed');

            angular.forEach(this.observerCallbacks, function (callback) {
                console.log('notification');
                callback();
            });
        };
    })
    angular.module('app2', ['app3']).controller('app2Controller', function ($scope, $rootScope, sharedService) {
        console.log('Controller 2 loaded');
        var updateCountry = function () {
            $scope.MyCountry = sharedService.Country;
        };

        sharedService.registerObserverCallback(updateCountry);
        console.log(sharedService);
        // this needs lazy loading
        // $rootScope = sharedService.scope;

        // console.log(sharedService.Country);
        // $scope.MyCountry = sharedService.Country;
    })
    angular.module('app1',['app1','app3']).controller('app1Controller',function($scope,$rootScope,sharedService)
    {
        $scope.Countries = ['Egypt', 'KSA'];
        $scope.Country = '';
        sharedService.scope = $rootScope;
        $scope.DrpChange = function () {
            //$stateParams.Country = $scope.Country;
            //$state.current.params.Country = $scope.Country;
            //console.log($state.current.params.Country);
            console.log(sharedService);
            sharedService.Country = $scope.Country;
            sharedService.notifyObservers();
            // this is not working because the rootscope is not shared
            $rootScope.$emit("Country.changed", $scope.Country);
        }
    })



    angular.bootstrap(document.getElementById("app2"), ['app2']);

see HTML at http://embed.plnkr.co/l0utIMp27qpbsao64Api/http://embed.plnkr.co/l0utIMp27qpbsao64Api/ 上查看 HTML

You are creating 2 completely separate angular apps.您正在创建 2 个完全独立的 Angular 应用程序。 That's why you're getting 2 instances.这就是为什么你会得到 2 个实例。 You want 1 app with 3 modules.您需要 1 个包含 3 个模块的应用程序。

First take out angular.bootstrap(document.getElementById("app2"), ['app2']);首先取出angular.bootstrap(document.getElementById("app2"), ['app2']); from index.html .来自index.html You're bootstrapping a second app there.您正在那里引导第二个应用程序。 Not what you want.不是你想要的。

Next, move ng-app="app1" to an element that contains both controllers like the body element.接下来,将ng-app="app1"到包含两个控制器(如body元素)的元素。

Also, in index.html change {{myCounty}} to {{MyCounty}} .此外,在index.html {{myCounty}}更改为{{MyCounty}} Case matters.案例很重要。

Finally in app.js change angular.module('app1',['app1','app3']) to angular.module('app1',['app2','app3']) .最后在app.js angular.module('app1',['app1','app3'])更改为angular.module('app1',['app2','app3']) I think that was what you meant to do in the first place.我认为这就是你最初打算做的。

Also, please post your index.html contents in the question.另外,请在问题中发布您的 index.html 内容。 A lot of the problems were in there.很多问题都在那里。 That way, if your link dies at some point, this question may still be helpful to others with similar problems.这样,如果您的链接在某个时候失效,这个问题可能仍然对其他有类似问题的人有帮助。

Here is a working Plunk .这是一个有效的Plunk

here's an demo/example showing a way to share data between tow different angular module : You should modify the code and use it according to your need/purpose :这是一个演示/示例,显示了一种在两个不同角度模块之间共享数据的方法:您应该修改代码并根据您的需要/目的使用它

angular.module('app.A', [])
.service('ServiceA', function() {
    this.getValue = function() {
        return this.myValue;
    };

    this.setValue = function(newValue) {
        this.myValue = newValue;
    }
});

angular.module('app.B', ['app.A'])
.service('ServiceB', function(ServiceA) {
    this.getValue = function() {
        return ServiceA.getValue();
    };

    this.setValue = function() {
        ServiceA.setValue('New value');
    }
});

Thanks & Cheers :-)谢谢和干杯:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM