gpt4 book ai didi

angularjs - 如何从一个模块向另一个模块发送消息?

转载 作者:行者123 更新时间:2023-12-02 23:19:40 24 4
gpt4 key购买 nike

Angular有模块间通信的集成解决方案吗?如何将数据从一个模块发送到另一个模块?也许有一些事件循环?

最佳答案

我将有一个通用模块,您的两个通信模块将依赖该模块。公共(public)模块将通过公开service来提供中介者模式的实现。可以向监听模块引发和广播事件。请参阅$emit , $on ,和$broadcast

我个人喜欢利用“隐藏”事件,以便将事件广播和处理封装在服务内部。您可以阅读有关此技术的更多信息 here

服务实现示例:

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');
}
};
});

确保您的模块依赖于 app.core

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

服务使用示例:

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();
};
});

关于angularjs - 如何从一个模块向另一个模块发送消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34161728/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com