Communication between modules in AngularJS

后端 未结 3 1271
别跟我提以往
别跟我提以往 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:50

    There are various ways module can interact or share information

    1. A module can be injected into another module, in which case the container module has access to all elements of the injected module. If you look at angular seed project, modules are created for directive, controllers, filters etc, something like this

      angular.module("myApp", ["myApp.filters", "myApp.services", "myApp.directives", "myApp.controllers"]) This is more of a re usability mechanism rather than communication mechanism.

    2. The second option is as explained by @Eduard would be to use services. Since services are singleton and can be injected into any controller, they can act as a communication mechanism.

    3. As @Eduard again pointed out the third option is to use parent controller using $scope object as it is available to all child controllers.

    4. You can also inject $rootScope into controllers that need to interact and use the $broadcast and $on methods to create a service bus pattern where controllers interact using pub\sub mechanism.

    I would lean towards 4th option. See some more details here too What's the correct way to communicate between controllers in AngularJS?

提交回复
热议问题