简体   繁体   中英

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 :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM