How to use emit/broadcast On Angular

Angular is very popular and powerful front-end library,Angular has many inbuilt function that useful to handle front-end layer of application easily,here we will discuss emit and broadcast method in respect of controller parent-child scope, if you are new-by in angular then it very helpful to access method of one controller to other.

What does broadcast :

The simple one line definition is “broadcast dispatches the event downwards to all child scopes”, that means from parent controller to downwards all child controller.

What does emit :

This is reverse of broadcast functionality “dispatches the event upwards through the parent controller scope hierarchy”.

There are following scenario can be occurred in application:

Option 1- firstCtrl is parent of the secondCtrl scope – dispatches the event downwards
Option 2- firstCtrl is parent of the secondCtrl scope – dispatches the event upwards
Option 3- no parent-child relation between firstCtrl and secondCtrl

Option 1:

FirstCtrl is parent of the SecondCtrl

for this case, you need to call $broadcast in firstCtrl,you need to define boradcast into FirstCtrl and listen this into SecondCtrl.
The sample example is below:

Option 2:

firstCtrl is parent of the secondCtrl scope – dispatches the event upwards

for this case, you need to call $emit in SecondCtrl,you need to define emit into SecondCtrl and listed this into FirstCtrl.The sample example is below:

Option 3:

No parent-child relation between firstCtrl and secondCtrl

In this case, You need to inject $rootScope into the controller and broadcast the event to all child scopes.