angularjs 中
broadcast与
emit $on的处理思想
-
对于Angular的controll之间的通信方式,我们可以常见有有几种方式,如可以通过
rootScope,还有通过
scope的作用域,当然还有一种个人觉得很好的通信方式就是
broadcast,
emit,$on来监听;
-
broadcast方式与
emit方式的区别
broadcast方式一种广播模式,就是父级发送一个消息时间,子级controller里面监听这个消息事件的函数就会执行;
emit与$broadcast方式相反,是子级controller发布一个消息事件,父级controller监听的函数执行;
两种方式平级的controller都不能收到消息事件,注意同一个controller里面都是可以捕获到消息事件的;
父子级controller
<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>
javascript如下:
phonecatControllers.controller('SelfCtrl', function($scope) {
$scope.click = function () {
$scope.$broadcast('to-child', 'child');
$scope.$emit('to-parent', 'parent');
}
});
phonecatControllers.controller('ParentCtrl', function($scope) {
$scope.$on('to-parent', function(d,data) {
console.log(data);
});
$scope.$on('to-child', function(d,data) {
console.log(data);
});
});
phonecatControllers.controller('ChildCtrl', function($scope){
$scope.$on('to-child', function(d,data) {
console.log(data);
});
$scope.$on('to-parent', function(d,data) {
console.log(data);
});
});
phonecatControllers.controller('BroCtrl', function($scope){
$scope.$on('to-parent', function(d,data) {
console.log(data);
});
$scope.$on('to-child', function(d,data) {
console.log(data);
});
});
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
同一个controller里面
<div ng-controller="Ctrl">
<h1>{{message1}}</h1>
<h2>{{message2}}</h2>
</div>
js代码:
angular.module('app', [])
.controller('Ctrl', ['$scope', function($scope) {
$scope.$on('msg1', function(e, msg) {
$scope.message1 = msg;
});
$scope.$on('msg2', function(e, msg) {
$scope.message2 = msg;
});
$scope.$emit('msg1', 'Hello Angular!');
$scope.$broadcast('msg2', 'Angular is magic!')
}]);
注意:
相比
emit冒泡方法,
broadcast广播方法要消耗更多的资源,因为广播事件会深入到该作用域的所有子孙作用域,跟单路径冒泡的
emit消耗的资源完全不是数量级。故而对于包含成数千子作用域又要追求较高性能的情况,可能需要考虑一下是否弃用
broadcast方法