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!
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!
$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.
$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
.
$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 $scope
s listen.
$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.