Listen to window events in an Angularjs service

后端 未结 4 2240
梦谈多话
梦谈多话 2020-12-17 23:21

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

相关标签:
4条回答
  • 2020-12-17 23:35

    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
      });
    
    0 讨论(0)
  • 2020-12-17 23:37

    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.

    0 讨论(0)
  • 2020-12-17 23:40

    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);
        });
    } ]);
    
    0 讨论(0)
  • 2020-12-17 23:40

    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,

    • Page A >> Page B (alert count 1) Page B >> Page A >> Page B (alert count 2) Page B >> Page A >> Page B (alert count 3)
    0 讨论(0)
提交回复
热议问题