Understanding $Broadcast(), $Emit() And $On() In AngularJS

AngularJS applications usually involve internally sending information (messages) across its different controllers, services, and factories.

Syntax:

Here we are broadcasting an event called castEvent with a data object which contains a message.

Here ae are emitting an event called emitEvent.

Even though via syntax they both seems to be same ther fire events in different directions.

Listening for an event
Listening for an event can be done via ‘$on’.

Syntax:

If we are broadcasting an event from ctrl1, to both ctrl2 and ctrl3, where ctrl2 and ctrl3 will be notified given that they are child controllers of one another.

$scope.$broadcast() allows us to send an event down the controller hierarchy, which means all child controllers of the controller which broadcasts the event will be notified of this event firing. If they are listening to the specific event, you’ll be able to do whatever you’d like with the event data.

Leave a Reply

Your email address will not be published. Required fields are marked *