作用域之间的通信:
1.在应用程序中建一个单例服务,然后通过这个服务处理所有子作用域的通信。
2.父子作用域之间的通信可以通过$emit $brodcast $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代码:
app.controller('SelfCtrl',function($scope){
$scope.click=function(){
$scope.$broadcast('to-child','child');
$scope.$emit('to-child','parent');
}
});
app.controller("parentCtrl",function($scope){
$scope.$on('to-parent',function(event,data){
console.log('PrentCtrl',data);//父级能得到值
});
$scope.$on('to-child',function(event,data){
console.log('ParentCtrl',data);//子级得不到
});
});
app.contorller('ChildCtrl',function($scope){
$scope.$on('to-child',function(event,data){
console.log('ChildCtrl',data); //子级能得到值
});
$scope.$on('to-parent',functoin(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)//平级得不到值
})
})
最终结果:
ParentCtrl parent
ChildCtrl child
$emit $broadcast 可传多个参数,$on也可以接收多个参数
在$on的方法中的event 事件参数 ,其对象的属性和方法如下
事件属性 | 目的 |
|
|
|
|
|
|
|
一个防止事件进一步传播(冒泡/捕获)的函数(这只适用于使用`$emit`发出的事件) |
|
|
这个方法实际上不会做什么事,但是会设置`defaultPrevented`为true。直到事件监听器的实现者采取行动之前它才会检查`defaultPrevented`的值。 |
|
|
如果调用了`preventDefault`则为true |
|