0

In one controller of my Angular 1.4.7 app I fire an event like so:

$rootScope.$broadcast('event:auth:login-finished');

then in another controller, I attempt to listen to this event with

$scope.$on('event:auth:login-finished', function () {
  console.debug('ROOT AUTH HANDLER CALLED');
});

For some reason, the handler is never called, even though the event is definitely being fired, am I doing something wrong?

Update

I've also tried listening to the root scope

$rootScope.$on('event:auth:login-finished', function () {
  console.debug('ROOT AUTH HANDLER CALLED');
});

But this doesn't get called either

  • Another common problem is that your controller gets instantiated after the event is broadcast. – Sunil D. May 06 '16 at 19:48
  • Can you please provide more information about when the event is fired? – Elka May 06 '16 at 19:55
  • Possible duplicate of [Broadcast not received in directive](http://stackoverflow.com/questions/36882975/broadcast-not-received-in-directive) – Estus Flask May 06 '16 at 22:32

2 Answers2

0

Use $rootScope.$on to catch it.

The key is to get the "root".

A.J.
  • 393
  • 1
  • 8
  • I would need to see more code to accurately diagnose the problem. $rootScope.$on should be defined before you trigger it (i.e. the location of this code should be before the call). You can also try $rootScope.$emit or $scope.$emit instead of $rootScope.$broadcast if you're trying to restrict scope. – A.J. May 09 '16 at 14:27
0

It depends on the relationship between the controllers. Calling $broadcast will fire the event to all child scopes. So if the $on is not in a child controller, then it won't fire.

Putting the $on on the rootScope should work.

$rootScope.$on('event:auth:login-finished', function () {
  console.debug('ROOT AUTH HANDLER CALLED');
});
Austin
  • 1,291
  • 10
  • 19