Home >Web Front-end >JS Tutorial >How do $on and $broadcast Enable Event Communication in Angular?
Angular provides two fundamental event communication methods, $on and $broadcast, which allow components within an application to communicate with each other. Understanding how these methods work is crucial for effective event handling in Angular applications.
$broadcast
When an event occurs in a controller, such as clicking an element in footer.html within the footerController, it can be broadcast to other parts of the application using $broadcast. This method takes an event name and optional arguments as parameters.
<code class="javascript">$rootScope.$broadcast('scanner-started');</code>
$on
Other components can subscribe to these events using $on. This method takes an event name and a callback function as parameters. When the event is broadcast, the callback function is triggered, providing access to any arguments passed with $broadcast.
<code class="javascript">$scope.$on('scanner-started', function(event, args) { // do what you want to do });</code>
Example
Consider the codeScannerController that requires a startScanner event to begin scanning a code. The footerController can trigger this event when an element is clicked on.
<code class="javascript">// In footerController $scope.startScanner = function() { $rootScope.$broadcast('scanner-started', { any: {} }); } // In codeScannerController $scope.$on('scanner-started', function(event, args) { var anything = args.any; // do what you want to do });</code>
Usage
$on and $broadcast are commonly used to facilitate communication between different components, such as between controllers, services, and directives. They allow events to be triggered and handled across the application, enabling a loosely coupled design.
The above is the detailed content of How do $on and $broadcast Enable Event Communication in Angular?. For more information, please follow other related articles on the PHP Chinese website!