Home > Web Front-end > JS Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-10-28 07:18:01
Original
557 people have browsed it

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>
Copy after login

$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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!