Home >Web Front-end >JS Tutorial >How Do `$scope.$emit` and `$scope.$on` Facilitate Event Communication in AngularJS Controllers?
Event Communication in Controllers using $scope.$emit and $scope.$on
$scope.$emit and $scope.$on are essential AngularJS methods for facilitating event communication between controllers. However, understanding their precise behavior is crucial for effective implementation.
The $emit Method
$emit dispatches an event from a controller, sending it upwards through the scope hierarchy. It allows controllers to communicate with parent scopes and potentially other child scopes.
The $on Method
$on listens for events emitted by other controllers. Its callback function receives an event object with details about the emitted event, including data passed along.
Matching Event Names
When using $emit and $on, it's important to use matching event names. The event name determines which controllers will receive the event.
Scope Relationships
The relationship between the scopes of the controllers determines which communication methods are effective.
Parent-Child Relationship
In a parent-child scope relationship, $broadcast in the parent controller (emitting) and $on in the child controller (listening) will suffice.
Example:
function firstCtrl($scope) { $scope.$broadcast('someEvent', [1,2,3]); } function secondCtrl($scope) { $scope.$on('someEvent', function(event, mass) { console.log(mass); }); }
No Parent-Child Relationship
If there's no parent-child relationship, injecting $rootScope in the controller and using $rootScope.$broadcast will ensure the event reaches all scopes.
Example:
function firstCtrl($rootScope) { $rootScope.$broadcast('someEvent', [1,2,3]); }
Event Dispatching from Child to Parent
To dispatch events from child to parent scopes, use $scope.$emit in the child controller and $scope.$on in the parent controller.
Example:
function firstCtrl($scope) { $scope.$on('someEvent', function(event, data) { console.log(data); }); } function secondCtrl($scope) { $scope.$emit('someEvent', [1,2,3]); }
The above is the detailed content of How Do `$scope.$emit` and `$scope.$on` Facilitate Event Communication in AngularJS Controllers?. For more information, please follow other related articles on the PHP Chinese website!