angularjsangularjs-factoryangularjs-rootscope

Propagating Scope Events from a Factory


Neither $rootScope.$broadcast nor $rootScope.$emit is working from my factory

I have $rootScope injected into the factory. The factory returns this function:

alertHook: function() {
  $rootScope.$broadcast('getRollups', 'finally');
}

I injected that factory into a directive and call the alertHook() function.

I am listening for getRollups like so:

$scope.$on( 'getRollups', function( evt, args ) {
    console.log( args );
  });

Lo and behold, nothing is logged to the console. I've also tried $emit instead of $broadcast.

Help please, before I go insane :)


Solution

  • With factories use $rootScope.$broadcast:

    angular.module("app",[])
    .factory("factory", function($rootScope) {
       return { broadcast: broadcast };
       function broadcast () {
          $rootScope.$broadcast("myEvent","from factory")
       }
    })
    .controller("ctrl",function($scope,factory) {
      $scope.$on("myEvent", function(ev,args) {
        console.log(ev.name,args);
      });
      $scope.clickMe = function() {
        factory.broadcast();
      };
    })
    <script src="//unpkg.com/angular/angular.js"></script>
    <body ng-app="app" ng-controller="ctrl">
      <button ng-click="clickMe()">Click me</button>
    </body>

    For more information, see