How to communicate between controllers of two different modules in AngularJs

前端 未结 2 668
太阳男子
太阳男子 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条回答
  • 2020-12-20 03:00

    your plunker has a very minor issue.

    change this

         angular.module('myApp', [])
    

    to

         angular.module('myApp', ['myNewApp'])
    
    0 讨论(0)
  • 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;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="firstModule">
    
      <div ng-controller="FirstController as vm">
        First Controller in module firstModule<br>
        <input type=text ng-model="vm.data.value" />
      </div>
    
      <div ng-controller="SecondController as vm">
        Second Controller in module secondModule<br>
        {{vm.data.value}}
      </div>
    </div>

    0 讨论(0)
提交回复
热议问题