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
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
});
Do you inject that service somewhere? Services will run only if you really injects them.
Additionally, it's better to use $window instead of window, so you'll be able to mock it later in your tests.
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);
});
} ]);
Problem:
"$window listener" listen multiple time.
Example:
Consider , we wrote a listener code in Page B. My starting page is Page A.
I added an alert in listener code in Page B.
$window.addEventListener('message', function (e) { alert() });
Lets Go,