$broadcast event not received by controller

user1491636 picture user1491636 · Jul 28, 2014 · Viewed 9.3k times · Source

So I have an angularjs app with several partial views and one controller per partial view. I also have a service which will $broadcast events from the $rootScope:

$rootScope.$broadcast('MyEvent', 'message');

Currently there is only one controller listening for events and I noticed that if I am not on the view that is associated to that one controller (via routes), then the event is never received in that controller and thus never loads the view associated to it. How can I ensure that the controller receives the event broadcast regardless of which view is active? I tried using $scope.$on('MyEvent')... and $rootScope.$on('MyEvent')... in my controller; neither seem to work.

Answer

Divya MV picture Divya MV · Aug 19, 2015

This is the expected behavior, as your partial views have individual controllers associated with them. The controller would be in scope only if the view is rendered.The controller comes in to scope only when your ng-controller directive is parsed in your partial view.So expect your controllers to be in scope only after loading the view associated with it.

In your case, when you broadcasted the event myEvent using $rootScope.$broadcast('MyEvent', 'message'); the controller you wanted to receive this event was not in scope.

to see this clearly put a breakpoint on your broadcast step and pause the execution to check the value of angular.element('[ng-controller=urControllerName]').scope() in console and you can see that it would be undefined meaning that the controller is not yet in scope.