Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Communication between modules in AngularJS

Tags:

angularjs

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?

like image 298
Dánjal Salberg Adlersson Avatar asked Jun 11 '13 12:06

Dánjal Salberg Adlersson


People also ask

How do you communicate between modules?

Communication between modules is done via the exchange of named objects with the event and object manager. Modules therefore do not depend on specific other modules being available in memory or having been run before, but only on whether the necessary data objects have been stored in the event or the object manager.

What is used to interact between modules?

Modules can interact among them in two ways: explicitly (by direct query) and inwardly (through event system).

Can we have multiple modules in AngularJS?

Yes, you can define multiple modules in angularJS as given below. The modularization in AngularJS helps us to keep the code clarity and easy to understand, as we can combine multiple modules to generate the application.


1 Answers

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?

like image 103
Chandermani Avatar answered Oct 02 '22 20:10

Chandermani