0

What is difference between $scope.$emit and $rootScope.$emit ?

I'm using it to emit from a directive to controller and it works un both ways!

vicky_864
  • 57
  • 8

3 Answers3

1

$scope.$emit allows the current scope and parents (including the rootScope) to listen for an event.

$rootScope.$emit allows only the rootScope to listen for a specific event.

cardeol
  • 2,218
  • 17
  • 25
0

$scope.$emit is useful when you want that $scope and all its parents and $rootScope able to hear the event. $scope.$emit is a child whining to their parents $scope.

And

$rootScope.$emit only lets other $rootScope listeners for catching it. This is useful when you don't want to notify every $scope.

Shaishab Roy
  • 16,335
  • 7
  • 50
  • 68
-1

$emit() sends changes to its parent scopes upward in the chain.

So, when you do $scope.$emit, you are sending a notification to the parent scope, which could be another $scope or might be $rootScope.
It basically works like childScope > parentScope(s).

Its opposite is .broadcast().

.broadcast() broadcasts changes to child scopes. So, if you broadcast from $rootScope then all the child $scopes listen.


From the docs:

$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.

Any exception emitted from the listeners will be passed onto the $exceptionHandler service.

Jai
  • 74,255
  • 12
  • 74
  • 103
  • This does a good job of explaining what `$scope.$emit` is but not what `$rootScope.$emit` is. `$rootScope.$emit` will only let other `$rootScope` listeners catch it. – ste2425 Feb 01 '16 at 13:48
  • @ste2425 never thought of it before but it seems to be invalid. – Jai Feb 01 '16 at 13:49