在 Angularjs 服务中监听窗口事件 [英] Listen to window events in an Angularjs service
问题描述
我想在我的 AngularJS 服务中监听窗口事件,以便我可以将它们广播到我的控制器.
I want to listen to the window events in my AngularJS service so that I can broadcast them to my controllers.
我有一个 Chrome 扩展程序,它使用 port.postMessage('Any Message');
发送任何消息.
I have a Chrome extension which sends any message using port.postMessage('Any Message');
.
我希望我的 angularjs 服务监听该消息并使用 $rootScope.$broadcast("Something occurred.");
I want my angularjs service to listen to that message and send it to the controller using $rootScope.$broadcast("Something occurred.");
在我的服务中,我正在尝试使用以下侦听器.
Inside my service, I am trying to do so with the following listener.
window.addEventListener('Any Message', function (event) {
if (event.origin != window.location.origin) {
return;
}
$rootScope.$broadcast("Something occurred.");
});
我也试过 $window
但我不知道为什么上面的代码不起作用.还有我的 IDE,jetbrains webstorms 将上面的代码片段归类为无法访问.
I also tried $window
but I don't know why the above code does not work. Also my IDE, jetbrains webstorms classify above code snippet as unreachable.
在此之前,我在控制器中使用了上面的代码并且运行良好.我没有在控制器中进行广播.现在我想把它移到服务中,这样所有控制器都应该能够从服务中监听它.
Before this, I used the above code in a controller and it worked fine. I wasn't doing broadcast in controller. Now I want to move this to the service so that all controllers should be able to listen to it from service.
推荐答案
这是我制作的工作示例 - 订阅 DOM 事件并将事件从服务广播到控制器:http://plnkr.co/edit/nk2aPt?p=preview
Here is working example I've made - with subscribing DOM event and broadcasting the event from service to controller: http://plnkr.co/edit/nk2aPt?p=preview
//this is service that creates subscription
app.service('serviceName', function($window, $rootScope) {
function subsFunc() {
$window.addEventListener('click', function(e) {
$rootScope.$broadcast('app.clickEvent', e);
})
}
return {
"subscribeMe": subsFunc }
});
//this will be in controller
$rootScope.$on('app.clickEvent', function(a, b) {
//a,b - event object details
});
这篇关于在 Angularjs 服务中监听窗口事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!