Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

javascript - Listen to window events in an Angularjs service

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

I have a Chrome extension which sends any message using port.postMessage('Any Message');.

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...