Communication between modules in AngularJS

后端 未结 3 1286
别跟我提以往
别跟我提以往 2020-12-23 23:20

I guess it is possible to have many angular-modules attached to different regions within one shellpage. But can modules in AngularJS \"talk\" to each other? If yes, how?

3条回答
  •  遥遥无期
    2020-12-23 23:47

    Using the service mechanism to communicate among module's controllers.

     (function () {
            'use strict';
    
        //adding moduleB as dependency to moduleA
    
        angular.module('Myapp.moduleA', ['Myapp.moduleB'])
          .controller('FCtrl', FCtrl)
          .service('sharedData', SharedData);
    
        //adding the dependency shareData to FCtrl
    
        FCtrl.$inject = ['sharedData'];
    
        function FCtrl(sharedData) {
    
          var vm = this;
          vm.data = sharedData.data;
        }
    
    
        //shared data service
        function SharedData() {
    
          this.data = {
            value: 'my shared data'
          }
    
        }
    
        //second module
        angular.module('Myapp.moduleB', [])
          .controller('SCtrl', SCtrl);
    
        SCtrl.$inject = ['sharedData'];
    
        function SCtrl(sharedData) {
    
          var vm = this;
          vm.data = sharedData.data;
        }
    
    
        })();
    

    And the HTML as follows:

    
    
    
      

提交回复
热议问题