Home > Article > Web Front-end > Information transfer between Controllers in Angular (second method): $emit, $broadcast, $on
<div ng-controller="ParentCtrl"> <!--父级--> <div ng-controller="SelfCtrl"> <!--自己--> <a ng-click="click()">click me</a> <div ng-controller="ChildCtrl"></div> <!--子级--> </div> <div ng-controller="BroCtrl"></div> <!--平级--> </div>
JS:
var app = 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); //父级能得到值 }); $scope.$on('to-child', function(event,data) { console.log('ParentCtrl', data); //子级得不到值 }); }); app.controller('ChildCtrl', function($scope){ $scope.$on('to-child', function(event,data) { console.log('ChildCtrl', data); //子级能得到值 }); $scope.$on('to-parent', function(event,data) { console.log('ChildCtrl', data); //父级得不到值 }); }); app.controller('BroCtrl', function($scope){ $scope.$on('to-parent', function(event,data) { console.log('BroCtrl', data); //平级得不到值 }); $scope.$on('to-child', function(event,data) { console.log('BroCtrl', data); //平级得不到值 }); });
Click click to run the result:
ChildCtrl child controller.
ParentCtrl parent
The event event parameter in the $on method, the properties and methods of its object are as follows
Event Properties | Purpose |
---|---|
event.targetScope | The scope to emit or propagate the original event |
event.currentScope | The scope of the event currently being processed |
event.name | Event name |
event.stopPropagation() | A function that prevents further propagation (bubbling/capturing) of an event (this only applies to events emitted using `$emit`) |
event.preventDefault() | This method will not actually do anything, but will set `defaultPrevented` to true. The event listener does not check the value of defaultPrevented until its implementer takes action. |
event.defaultPrevented | True if `preventDefault` is called |
The above is the detailed content of Information transfer between Controllers in Angular (second method): $emit, $broadcast, $on. For more information, please follow other related articles on the PHP Chinese website!