Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does $rootScope.$emit broadcast to all controllers including itself?

I'm using $rootScope.$emit() and $rootScope.$on() to broadcast and listen for state changes within my Angular app.

In some cases multiple controllers can both emit and listen for the same events. If I had the following code within the same controller would this controller run its .$on code when it emits the event, or is the event only broadcast to other controllers?

$rootScope.$emit('adminChanged');
...
$rootScope.$on('adminChanged', function() {
  getCustomerInfo();
});
like image 859
MattDionis Avatar asked Dec 11 '22 21:12

MattDionis


2 Answers

See the angular docs for the answer: (emphasis mine)

On $emit:

$emit(name, args); Dispatches an event name upwards through the scope hierarchy notifying the registered $rootScope.Scope listeners.

The event life cycle starts at the scope on which $emit was called. All listeners listening for name event on this scope get notified. Afterwards, the event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.

On $broadcast:

$broadcast(name, args); Dispatches an event name downwards to all child scopes (and their children) notifying the registered $rootScope.Scope listeners.

The event life cycle starts at the scope on which $broadcast was called. All listeners listening for name event on this scope get notified. Afterwards, the event propagates to all direct and indirect scopes of the current scope and calls all registered listeners along the way. The event cannot be canceled.

(Also, heed rob's comment about which one to use!)

like image 136
doldt Avatar answered May 06 '23 02:05

doldt


$scope.$emit up, $scope.$broadcast down

Using $scope.$emit will fire an event up the $scope. Using $scope.$broadcast will fire an event down the $scope. Using $scope.$on is how we listen for these events. A quick example:

// firing an event upwards
$scope.$emit('myCustomEvent', 'Data to send');

// firing an event downwards
$scope.$broadcast('myCustomEvent', {
  someProp: 'Sending you an Object!' // send whatever you want
});

// listen for the event in the relevant $scope
$scope.$on('myCustomEvent', function (event, data) {
  console.log(data); // 'Data to send'
});

We could fire an event down from ParentCtrl to SiblingOneCtrl using $broadcast:

app.controller('ParentCtrl',
  function ParentCtrl ($scope) {

  $scope.$broadcast('parent', 'Some data'); // going down!

});

app.controller('SiblingOneCtrl',
  function SiblingOneCtrl ($scope) {

  $scope.$on('parent', function (event, data) {
    console.log(data); // 'Some data'
  });

});
like image 30
Megha Nagpal Avatar answered May 06 '23 00:05

Megha Nagpal