文章目录
  1. 1. 来个栗子
  2. 2. 引用文章

Angular的作用域在本质上是分层次的:他们可以通过父子关系来回沟通,但作用域通常不是共享变量的,他们执行的功能往往各不相同,跟在父树上的位置无关。共享数据使用服务,作用域间通信使用事件。

Angular事件系统并不与浏览器的事件系统相通。这意味着,我们只能在作用域上监听Angular事件而不是DOM事件。
事件通信是按照作用域链来进行传播。使用scope()原型上的$emit进行向上传播,$broadcast 进行向下传播,$on 进行事件接收。

来个栗子

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
34
35
36
37
38
39
40
41
42
43
44
<body>
<div ng-controller="ParentCtrl">
<div ng-controller="SelfCtrl">
<button ng-click="click()">click me</button>
<div ng-controller="ChildCtrl"></div>
</div>
<div ng-controller="BroCtrl"></div>
</div>
<script type="text/javascript">
angular.module('myApp', [])
.controller('ParentCtrl', function($scope) {
$scope.$on('to-child', function(e, d) {
console.log('broadcast---parent');
});
$scope.$on('to-parent',function(){
console.log("emit---parent");
})
})
.controller('SelfCtrl', function($scope) {
$scope.click = function () {
$scope.$broadcast('to-child', 'haha');
$scope.$emit('to-parent', 'hehe');
$scope.$on('to-parent',function(){
console.log("emit--self");
});
$scope.$on('to-child',function(){
console.log("broadcast--self");
})
}
})
.controller('ChildCtrl', function($scope){
$scope.$on('to-child', function(e, d) {
console.log('broadcast---child', d);
});
})
.controller('BroCtrl', function($scope){
$scope.$on('to-child', function(e, d) {
console.log('broadcast--bro');
});
$scope.$on('to-parent', function(e, d) {
console.log('emit--bro');
});
});
</script>

在这个例子中作用域的嵌套关系是这样的:

> ParentCtrl
    > SelfCtrl
      > ChildCtrl
    > BroCtrl

根据使用$emit来向上传播事件、使用$broadcast来向下传播事件、使用$on 来接收事件这样的规则,若是想从SelfCtrl向ParentCtrl传递消息则应使用$emit方法,而且ChildCtrl是收不到的。同样给ChildCtrl传递消息应使用$broadcast方法,当然ParentCtrl是收不到消息的。

查看console的结果会发现无论是$emit还是$broadcast都不会在自己的作用域上接收消失,实际上也没有这个必要。

事件的消息传播是按照作用域链进行,若是SelfCtrl 想和兄弟作用域BroCtrl进行通信呢?我觉得可以这样,SelfCtrl可以先发消息通知ParentCtrl,ParentCtrl收到消息后再通知BroCtrl,这样就能通信了。

还有种不太好的方式,就是将 $emit,$broadcast,$on全部放在$rootScope上,这样发消息是都能收到的,但是这样会污染$rootScope。

引用文章

  1. angularjs的事件 $broadcast and $emit and $on
文章目录
  1. 1. 来个栗子
  2. 2. 引用文章