In AngularJS, event handling is crucial for communication between different parts of the application. AngularJS provides $event
, $emit
, and $broadcast
to handle events efficiently within controllers and directives.
1. Understanding $event
The $event
object in AngularJS represents the DOM event that triggered a function.
Usage in Templates
<button ng-click="handleClick($event)">Click Me</button>
Usage in Controller
$scope.handleClick = function(event) {
console.log("Event Type:", event.type); // Outputs: click
};
$event
helps access event properties like target
, type
, and clientX
.
2. $emit()
– Propagating Events Upwards
$emit()
sends an event upwards through the scope hierarchy, notifying parent controllers and $rootScope
.
Example
$scope.$emit("customEvent", { message: "Hello Parent!" });
Listening in Parent Controller
$scope.$on("customEvent", function(event, data) {
console.log("Received in Parent:", data.message);
});
Use $emit()
to notify parent controllers about child events.
3. $broadcast()
– Propagating Events Downwards
$broadcast()
sends an event downwards to all child scopes.
Example
$scope.$broadcast("childEvent", { info: "Hello Children!" });
Listening in Child Controller
$scope.$on("childEvent", function(event, data) {
console.log("Received in Child:", data.info);
});
Use $broadcast()
to notify child controllers.
4. $on()
– Listening for Events
Both $emit()
and $broadcast()
require $on()
to listen for events.
$scope.$on("someEvent", function(event, data) {
console.log("Event received:", data);
});
$on()
is essential for handling custom events.
5. Practical Example: Parent-Child Communication
HTML
<div ng-controller="ParentController">
<button ng-click="sendMessage()">Send to Child</button>
<div ng-controller="ChildController">
<p>{{childMessage}}</p>
</div>
</div>
JavaScript
app.controller("ParentController", function($scope) {
$scope.sendMessage = function() {
$scope.$broadcast("messageEvent", { text: "Hello Child!" });
};
});
app.controller("ChildController", function($scope) {
$scope.$on("messageEvent", function(event, data) {
$scope.childMessage = data.text;
});
});
Parent uses $broadcast()
, child listens using $on()
.
6. Global Event Handling with $rootScope
To listen to events globally, use $rootScope
.
Emitting from Any Controller
$rootScope.$emit("globalEvent", { status: "Success" });
Listening in Any Controller
$rootScope.$on("globalEvent", function(event, data) {
console.log("Global Event Received:", data.status);
});
$rootScope
events are accessible from any controller.
7. Cleaning Up Event Listeners
To avoid memory leaks, remove event listeners when a scope is destroyed.
var eventListener = $scope.$on("someEvent", function(event, data) {
console.log("Event received:", data);
});
$scope.$on("$destroy", function() {
eventListener(); // Unsubscribes from event
});
Always clean up listeners using $destroy
.