- $emit can only pass event and data to the parent controller
- $broadcast can only pass event and data to child controller
- $on for receiving event and data
Examples are as follows
HTML code
<div ng-controller= "Parentctrl" > <!--parent-to- <div ng-controller= "Selfctrl" > <!-- Self- -<a ng-click= "click ()" >click me</a> <div ng-controller= "Childctrl" ></div> <!--children- </div> <div ng-controller= "Broctrl" ></div> <!--level-to- </div>
JS Code
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. }); });
Final result
Parentctrl Child
Childctrl Parent
$emit and $broadcast can pass multiple parameters, $on can also receive multiple parameters.
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 |
Feel much more convenient than service in different controller communication ~ ~
< Span class= "Hljs-name" > < Span class= "hljs-comment" >< Span class= "Hljs-tag" >&NBSP;
Use of angularjs--$on, $emit and $broadcast