How to communicate between controllers of two different modules in AngularJs

前端 未结 2 698
太阳男子
太阳男子 2020-12-20 02:52

I want to know that can we communicate between two different controllers in AngularJS. Suppose I have Two modules,
Plunker: http://plnkr.co/edit/if0MQwlx9WHrD8XnMi2t?p=

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-20 03:14

    As @JB Nizet says, you do it the exact same way. You use a service to communicate between two controllers.

    One module needs to have the other module as a dependency. This is always a one-way dependency. I have made secondModule a dependency of firstModule.

    As well, the value in the service is stored in an object called data. This is because JavaScript does not pass values by reference -- but does pass objects by reference. So this is a form of boxing.

    angular.module('firstModule', ['secondModule'])
      .controller('FirstController', FirstController)
      .service('sharedData', SharedData);
    
    FirstController.$inject = ['sharedData'];
    function FirstController(sharedData) {
      
      this.data = sharedData.data;
    }
    
    function SharedData() {
    
      this.data = {
        value: 'default value'
      }
    
    }
    
    angular.module('secondModule', [])
      .controller('SecondController', SecondController);
    
    SecondController.$inject = ['sharedData'];
    function SecondController(sharedData) {
      
      this.data = sharedData.data;
    }
    
    
    First Controller in module firstModule
    Second Controller in module secondModule
    {{vm.data.value}}

提交回复
热议问题