Home >Web Front-end >JS Tutorial >How do $on and $broadcast Enable Event Communication in Angular?

How do $on and $broadcast Enable Event Communication in Angular?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-28 07:18:01634browse

How do $on and $broadcast Enable Event Communication in Angular?

Event Communication with $on and $broadcast 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn