Why do we use $rootScope.$broadcast in AngularJS?
The $rootScope.$broadcast is used to broadcast a “global” event that can be caught by any listener of that particular scope. The descendant scopes can catch and handle this event by using $scope.$on.
$rootScope.$broadcast(name, args) $scope.$on(name, listener);
- listener: It is used to specify the function to call when the event is caught.
- Create a ParentController from which you would want to raise/broadcast an event.
- Use $rootScope.$broadcast in AngularJS to broadcast the event from the ParentController.
- Create a ChildController or an ExternalController (i.e., not a direct descendant of the ParentController) to catch and handle the event.
- Use $scope.$on in AngularJS to catch the respective event.
Example: This example uses $rootScope.$broadcast to raise an event.