- $emit can only pass event and data to the parent controller ($emit (name, args))
- $broadcast can only pass event and data to Child controller ($broadcast (name, args))
- $on for receiving event and data ($on (name, listener))
<DivNg-controller= "Parentctrl"> <!--Parent Level - <DivNg-controller= "Selfctrl"> <!--own - <aNg-click= "click ()">Click Me</a> <DivNg-controller= "Childctrl"></Div> <!--sub-level - </Div> <DivNg-controller= "Broctrl"></Div> <!--Lateral -</Div>
varApp = Angular.module (' myApp '), []); App.controller (' Selfctrl ',function($scope) {$scope. Click=function() {$scope. $broadcast (' To-child ', ' child '); $scope. $emit (' To-parent ', ' parent '); }}); App.controller (' Parentctrl ',function($scope) {$scope. $on (' To-parent ',function(event,data) {Console.log (' Parentctrl ', data);//The parent can get the value }); $scope. $on (' To-child ',function(event,data) {Console.log (' Parentctrl ', data);//children cannot get a value });}); App.controller (' Childctrl ',function($scope) {$scope. $on (' To-child ',function(event,data) {Console.log (' Childctrl ', data);//The child can get the value }); $scope. $on (' To-parent ',function(event,data) {Console.log (' Childctrl ', data);//The parent does not get a value });}); App.controller (' Broctrl ',function($scope) {$scope. $on (' To-parent ',function(event,data) {Console.log (' Broctrl ', data);//no value on the same lateral. }); $scope. $on (' To-child ',function(event,data) {Console.log (' Broctrl ', data);//no value on the same lateral. });});
The event arguments in the $on method, the properties and methods of their objects are as follows
Event Properties |
Purpose |
Event.targetscope |
Emit or propagate the scope of the original event |
Event.currentscope |
The scope of the event currently being processed |
Event.name |
Event name |
Event.stoppropagation () |
A function to prevent further propagation (bubbling/trapping) of events (this applies only to events emitted using ' $emit ') |
Event.preventdefault () |
This method does not actually do anything, but will set ' defaultprevented ' to true. It does not check the value of ' defaultprevented ' until the event listener's implementation takes action. |
event.defaultprevented |
True if ' preventdefault ' is called |
Use of $on, $emit and $broadcast