听窗口事件在Angularjs服务 [英] Listen to window events in an Angularjs service

查看:149
本文介绍了听窗口事件在Angularjs服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要听我的AngularJS服务窗口事件,这样我可以将它们传播到我的控制器。

I want to listen to the window events in my AngularJS service so that I can broadcast them to my controllers.

我在使用 port.postMessage('的任何消息'),它发送的任何消息的Chrome扩展;

我希望我的angularjs服务收听该消息,并用它给控制器 $ rootScope $广播(某事发生了。);

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.");
});

我也试过 $窗口,但我不知道为什么上面的code不起作用。也是我的IDE中,JetBrains公司webstorms上面的分类code段为不可达。

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.

在这之前,我使用上述code在控制器和它的工作的罚款。我不是在做着控制器播出。现在我想这个移动到服务,使所有控制器应该能够从服务中收听。

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=$p$pview

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆