PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, July 11, 2022

[FIXED] How to send message from one module to another?

 July 11, 2022     angularjs, messages     No comments   

Issue

Does angular have any integrated solutions for intermodule communications? How I can send data from one module to another? Maybe there's some eventloop?


Solution

I would have a common module that your two communicating modules would depend on. The common module would provide an implementation of the Mediator pattern, by exposing a service that can raise and broadcast events to listening modules. See $emit, $on, and $broadcast

I personally like to utilize "hidden" events, so that the events broadcast and handling are encapsulated inside of the service. You can read more about this technique here.

Example Service implementation:

angular.module('app.core').factory('NotifyService', function($rootScope) {
    return {
        onSomethingChanged: function(scope, callback) {
            var handler = $rootScope.$on('event:NotifyService.SomethingChanged', callback);
            scope.$on('$destroy', handler);               
        },
        raiseSomethingChanged: function() {
            $rootScope.$emit('event:NotifyService.SomethingChanged');
        }
    };
});

Make sure your modules depend on app.core

angular.module('module1', ['app.core']);
angular.module('module2', ['app.core']);

Example service usage:

angular.module('module1').controller('SomeController', function($scope, NotifyService) {
    NotifyService.onSomethingChanged($scope, function somethingChanged() {
        // Do something when something changed..
    });
});

angular.module('module2').controller('SomeOtherController', function($scope, NotifyService) {

    function DoSomething() {
        // Let the service know that something has changed, 
        // so that any listeners can respond to this change.
        NotifyService.raiseSomethingChanged();
    };
});


Answered By - Michael G
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing