如何从一个模块发送消息到另一个? [英] How to send message from one module to another?
问题描述
角是否有模块间通信的任何集成的解决方案?
我如何从一个模块发送数据到另一个?也许有一些事件循环?
我想有你的两个通信模块,将取决于一个通用模块。
常见的模块将提供Mediator模式的实现,通过暴露,可以提高和广播一个服务事件监听模块。请参见 $放出,的上 $和的 $
我个人喜欢使用隐藏的事件,使广播和处理的事件都封装在服务内。你可以阅读更多关于这项技术的<一个href=\"http://www.$c$clord.net/2015/05/04/angularjs-notifying-about-changes-from-services-to-controllers/\"相对=nofollow>此处。
示例服务实现:
angular.module('app.core')。工厂('NotifyService',函数($ rootScope){
返回{
onSomethingChanged:功能(范围,回调){
VAR处理器= $ rootScope在$('事件:NotifyService.SomethingChanged',回调)。
范围在$('$毁灭',处理程序)。
},
raiseSomethingChanged:功能(){
$ rootScope发出$('事件:NotifyService.SomethingChanged')。
}
};
});
确保你的模块依赖于app.core
angular.module('模块1',['app.core']);
angular.module('模块2',['app.core']);
示例服务使用:
angular.module('模块1')。控制器('SomeController',函数($范围,NotifyService){
NotifyService.onSomethingChanged($范围,功能somethingChanged(){
//做一些事情时,事情发生了转变..
});
});angular.module('模块2')。控制器('SomeOtherController',函数($范围,NotifyService){ 函数DoSomething的(){
//让服务知道事情已经改变,
//使任何听众可以应对这种变化。
NotifyService.raiseSomethingChanged();
};
});
Does angular have any integrated solutions for intermodule communications? How I can send data from one module to another? Maybe there's some eventloop?
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();
};
});
这篇关于如何从一个模块发送消息到另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!