Understand $broadcast, $emit and $events in AngularJS using example
One of our friends was recently asked about $Emit and $Broadcast in Angular. This article will focus on some of the questions around them.
Explain $broadcast, $emit and On $events ?
Controllers are one of the fundamental building blocks in AngularJs so communication between these controllers also becomes a very important thing. But communication between these controllers can become complicated if the controllers are nested.
For example in the below code you can see we have three controllers which are nested inside each other. "Child2" is nested inside "Child1" and "Child1" inside "Parent".
So now if we want to propagate event from Parent -> Child1 -> Child2 then use "$broadcast" and if you want to propagate vice-versa we need to use "$emit".
"on" method is where we write code which will be executed when the events propagates from top to bottom or vice-versa.
Below is the code of the "Parent" and "Child" controllers. You can see we have implemented code in the "on" events. You can also see we have called "$broadcast" from the parent to the child controllers and "$emit" from the child to the parent.
Below is the code where we have called the methods of the controllers.
How can we stop propogation in "$emit" and "$broadcast"?
To stop propagation from "emit" we need to call "stopPropagation" method as shown in the below code. This will stop propagation to all the child nested controllers.
To stop "$broadcast" we need to set "defaultPrevented" to true.
And then later in the child controllers we need to check if it's true then just return. Putting on other words for "$broadcast" we do not have real stop propogation it's just a flag with return logic.
$scope.broadcast vs $rootScope.broadcast ?
"$rootScope.broadcast" will notify all "$rootscope.on" and "$scope.on" while "$scope.broadcast" will notify only "$scope.on" methods below the nested objects.
"$rootscope.emit" is pointless as "rootscope" does not have parent.
How to unsubscribe from "$broadcast" and "$emit"?
In order to unsubscribe we need to first get reference of the "$scope.$on" method and then unregister the same by invoking that reference as shown in the below code.
Do not forget to watch our below Angular interview questions and answers series :-