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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.