Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 874
SamFast Avatar asked Feb 07 '15 13:02

SamFast


People also ask

How do I use $Watch in AngularJS?

The angular JS $watch function is used to watch the scope object. The $watch keep an eye on the variable and as the value of the variable changes the angular JS $what runs a function. This function takes two arguments one is the new value and another parameter is the old value.

What is $document in AngularJS?

A jQuery or jqLite wrapper for the browser's window.

Which function should we use to add event listener in a directive?

The ngOn directive adds an event listener to a DOM element via angular. element().


2 Answers

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
  });
like image 51
shershen Avatar answered Oct 17 '22 04:10

shershen


Something like this might help:

var app = angular.module('app', []);

app.run(["$window", "$rootScope", function($window, $rootScope) {

    $window.addEventListener('message', function(e) {

        $rootScope.$broadcast('message', e.data);
    });
} ]);
like image 25
Rian Avatar answered Oct 17 '22 03:10

Rian