VOOZH about

URL: https://www.geeksforgeeks.org/angular-js/why-do-we-use-rootscope-broadcast-in-angularjs/

⇱ Why do we use $rootScope.$broadcast in AngularJS? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Why do we use $rootScope.$broadcast in AngularJS?

Last Updated : 2 Aug, 2024

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.

Syntax:

$rootScope.$broadcast(name, args)
$scope.$on(name, listener);

Parameter value:

  • listener: It is used to specify the function to call when the event is caught.

Approach:

  • 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.

Output:

Comment

Explore