How do I communicate between scopes?
1. Create a singleton service, and then use this service to handle all child-scoped traffic.
2. Handle communication through events in the scope. But there are some limitations to this approach; For example, you can't propagate events extensively across all monitoring scopes. You must choose whether to communicate with the parent scope or the child scope.
$on, $emit, and $broadcast make it easy to transfer event and data between controllers.
$broadcast, $emit events must be triggered by other events (Ng-click, and so on), rather than simply writing one of these.
$on can write directly, because it belongs to listening and receiving data.
$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
Example:
HTML code
<div ng-controller= "Parentctrl" > <!--Parent--
<div ng-controller= "Selfctrl" > <!--yourself--
<a ng-click= "click ()" >click me</a>
<div ng-controller= "Childctrl" ></div> <!--children--
</div>
<div ng-controller= "Broctrl" ></div> <!--
</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.
});
});
$emit and $broadcast can pass multiple parameters, $on can also receive multiple parameters.
Event arguments in the $on method:
Event.name Event Name
Event.targetscope to emit or propagate the scope of the original event
Event.currentscope the scope of the event that is currently being processed
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 sets defaultprevented to true. It does not check the value of the defaultprevented until the event listener's implementation takes action.
event.defaultprevented true if Preventdefault is called
AngularJS $on $broadcast $emit