AngularJS 事件广播与接收 $broadcast,$emit,$on 作用域间通信 封装factory服务 发布订阅
不同作用域之间通过组合使用$broadcast,$emit,$on的事件广播机制来进行通信。
一、说明
1、广播
$broadcast
说明:将事件从父级作用域传播至本作用域及子级作用域。
格式:$broadcast(eventName,args)
$emit
说明:将事件从子级作用域传播至本作用域及父级作用域,直至根作用域。
格式:$emit(eventName,args)
2、接收
$on
说明:在作用域中监控从子级或父级作用域中传播过来的事件及相应的数据。
格式:$on(eventName,function(event,data){ })
event说明:
event.targetScope //获取传播事件的作用域
event.currentScope //获取接收事件的作用域
event.name //传播的事件的名称
event.stopPropagation() //阻止事件进行冒泡传播,仅在$emit事件中有效 ,当前作用域的上层作用域就不能再接收到消息事件
event.preventDefault() //阻止传播事件的发生
event.defaultPrevented //如果调用了preventDefault事件则返回true
二、例子
1、$scope.$emit
由子作用域向上级作用域传播数据。
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<meta charset="utf-8" />
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<script>
var myApp = angular.module("myApp", []); //控制器Parent
myApp.controller("Parent", function ($scope, $window) {
$scope.name = "Parent";
$scope.$on("fromChild", function (event, data) {
$window.alert("当前节点" + event.currentScope.name + ",截获到了来自" + data.divName + "的事件:" + event.name + ",它的作用是" + data.description);
}); });
//控制器Child
myApp.controller("Child", function ($scope, $window) {
$scope.toTop = function () {
//向上传播的事件,eventName:'fromChild', data:oneObject
$scope.$emit("fromChild", { divName: "child", description: "向上播数据" });
}; });
</script> </head>
<body>
<form>
<div ng-controller="Parent">
<div ng-controller="Child">
<input type="button" ng-click="toTop()" value="向上传播事件" />
</div>
</div>
</div>
</form>
</body>
</html>
运行结果

2、event.stopPropagation()
阻止事件进行冒泡传播,仅在$emit事件中有效 ,当前作用域的上层作用域就不能再接收到消息事件。
上个例子原来应该rootScope也能收到事件消息,如果加一句event.stopPropagation(),rootScope就不能收到事件数据。
代码修改如下:
//控制器Parent
myApp.controller("Parent", function ($scope, $window) {
$scope.name = "Parent";
$scope.$on("fromChild", function (event, data) {
$window.alert("当前节点" + event.currentScope.name + ",截获到了来自" + data.divName + "的事件:" + event.name + ",它的作用是" + data.description);
event.stopPropagation();
}); });
三、项目实例
子作用域 childScope
<div class="panel-heading" style="border-radius: 5px 5px 0 0; background-color: #608FB7;padding:10px;">
<strong>
{{focusedInput.inputType}}: #{{focusedInput.tooth.code2}}
{{focusedInput.toothSurface|toToothSurfaceString}}
{{focusedInput|toPerioInputPositionName}}
</strong>
</div>
<div class="panel-body perio-input-board" style="padding:5px;margin-left:8px;">
<div style="width: 180px;float:left" class="perio-input-number-board">
<button type="button" class="btn btn-lg btn-default" ng-click="setValue(1)">1</button>
</div> </div>
$emit向上层作用域发送消息广播,消息名称“perioInputFinished”,消息数据对象$scope.focusedInput
var setValue = function (value) {
if ($scope.focusedInput) {
$scope.$emit('perioInputFinished', $scope.focusedInput);
}
};
上级作用域parentScope
注册和接收,消息事件“perioInputFinished”,后又向子作用域广播,消息“perioValueChanged”,这样发送消息源作用域的兄弟作用域也可以收到消息事件
var init = function () {
//监控消息广播
$scope.$on('perioInputFinished', onPerioInputFinished);
};
//监控到后,接收又广播
var onPerioInputFinished = function (event, perioInput) {
$scope.$broadcast('perioValueChanged', perioInput);
};
下级作用域childScope1
接收到“perioValueChanged”消息后,通过名称联系,进行最终处理,onPerioValueChanged
var onPerioValueChanged = function (event, perioInput) {
if (perioInput.arch == $scope.arch && perioInput.toothSurface == $scope.toothSurface
&& (perioInput.inputType == 'PD' || perioInput.inputType == 'GM')) {
refreshLine();
}
};
var init = function () {
$scope.$on('perioValueChanged', onPerioValueChanged);
};
四、封装成服务factory方式
发布订阅模式
app.factory('eventAggregator', ['$log', '$rootScope', function ($log, $rootScope) {
'use strict';
var events = {
ChargeOrderCreated: 'ChargeOrderCreated',
SelectedEmployee: 'SelectedEmployee'
};
var publish = function (event, eventData, sender) {
$log.debug('[eventAggregator] publish(): ' + event);
$rootScope.$broadcast(event, eventData, sender);
};
$('body').on('sidebar-toggled', function (event, isCollapsed) {
$rootScope.isSideBarCollapsed = isCollapsed;
publish(events.AppSideBarToggled, null);
});
return {
events: events,
publish: publish,
subscribe: function (scope, event, callback) {
return scope.$on(event, callback);
}
};
}
]);
使用方式:
订阅:$scope.$on
var subscribeEvent = function () {
eventAggregator.subscribe($scope, eventAggregator.events.ChargeOrderCreated, refresh);
};
发布:$rootScope.$broadcast
eventAggregator.publish(eventAggregator.events.ChargeOrderCreated, chargeData, eventSender);
AngularJS 事件广播与接收 $broadcast,$emit,$on 作用域间通信 封装factory服务 发布订阅的更多相关文章
- angularJS 事件广播与接收[转]
路由的事件 事件这个词在前端出现的频率真是高,根本拦不住,哪都是.$route服务在路由过程中的每个阶段都会触发不同的事件,可以为这些不同的路由事件设置监听器并做出响应. 一共有4个事件用来监听路由的 ...
- angularJS 事件广播与接收
发送消息: $scope.$emit(name, data) 或者 $scope.$broadcast(name, data); 接收消息: $scope.on(name,function(event ...
- AngularJS 事件广播与接收 $emit $broadcast $on
AngularJS中的作用域scope有一个非常有层次和嵌套分明的结构. 其中它们都有一个主要的$rootScope(也就说对应的Angular应用或者ng-app),然后其他所有的作用域部分都是继承 ...
- Angularjs中的事件广播 —全面解析$broadcast,$emit,$on
Angularjs中不同作用域之间可以通过组合使用$broadcast,$emit,$on的事件广播机制来进行通信 介绍: $broadcast的作用是将事件从父级作用域传播至子级作用域,包括自己.格 ...
- angularjs事件传递$on、$emit和$broadcast
如何在作用域之间通信呢? 1.创建一个单例服务,然后通过这个服务处理所有子作用域的通信. 2.通过作用域中的事件处理通信.但是这种方法有一些限制:例如,你并不能广泛的将事件传播到所有监控的作用域中.你 ...
- [spring源码学习]九、IOC源码-applicationEventMulticaster事件广播
一.代码实例 回到第IOC的第七章context部分,我们看源码分析部分,可以看到在spring的bean加载之后的第二个重要的bean为applicationEventMulticaster,从字面 ...
- VB.net Wcf事件广播(订阅、发布)
这篇东西原写在csdn.net上,最近新开通了博客想把零散在各处的都转移到一处. 一.源起 学WCF有一段时间了,可是无论是微软的WebCast还是其他网上的教程,亦或我购买的几本书中,都没有怎么 ...
- Android广播机制:Broadcast
转载:Android总结篇系列:Android广播机制 1.Android广播机制概述 Android广播分为两个方面:广播发送者和广播接收者,通常情况下,BroadcastReceiver指的就是广 ...
- AngularJS学习之旅—AngularJS 事件(十四)
1.AngularJS 事件 ng-click ( 适用标签 :所有,触发事件:单击): ng-dblclick( 适用标签 :所有,触发事件:双击): ng-blur(适用标签 : a,input, ...
随机推荐
- 简单选择排序(js版)
简单选择排序 基本思想:通过n-i次关键字间的比较,从n-i+1个记录中选出关键字最小的记录,并和第i个记录交换.(废话不多说,先看代码). function SelectSort(arr){ var ...
- Chat room
/* Vasya has recently learned to type and log on to the Internet. He immediately entered a chat room ...
- Android.DebugTools.Traceview & dmtracedump
1. Android 调试工具之Traceview http://www.cnblogs.com/devinzhang/archive/2011/12/18/2291592.html TraceVie ...
- nodejs 开发服务端 child_process 调试方法(1)
由于最近正在做一个服务端项目,采用了nodejs引擎开发,主要是master-worker工作机制;主进程可以直接调试,但是子进程调试好像有点麻烦,我没有找到好的方法; worker这里,我分拆成了几 ...
- 20172306《Java程序设计与数据结构》第十周学习总结
20172306<Java程序设计>第十周学习总结 教材学习内容总结 本章主要的讲的是集合有关的知识: 1.集合与数据结构 - 集合是一种对象,集合表示一个专用于保存元素的对象,并该对象还 ...
- Python的程序入口 __name__属性
python中每个模块都有一个 '__name__' 属性,当其值为 '__main__' 时,表名该模块自身在运行,否则是被引入的. 当一个模块被当做一个整体调用的时候,模块名.__name__ 的 ...
- [FreeMind] 绘制思维时遇到的常见问题解决办法
如何改变节点的摆放方向? 如果是新建节点,选择要放置节点的那一侧,按enter键,或者鼠标右键,插入平行节点即可. 如果是已经建好的节点,可以用ctrl+x, ctrl+v粘贴到另一边,或者选中子节点 ...
- Valid Mountain Array LT941
Given an array A of integers, return true if and only if it is a valid mountain array. Recall that A ...
- Java,JavaScript,jQuery,jSP,js
js是javascript文件的文件后缀,就像 a.txt 这个.txt是后缀一样 jsp是jsp网页文件的后缀,而jsp是java web 的表现层的一种技术 jquery 是一个函数库,基于jav ...
- g2o相关问题cs.h,以及no matching function for call to ‘g2o::OptimizationAlgorithmLevenberg::OptimizationAlgorithmLevenberg(Block*&)
1.对于cs.h找不到的情况 1)编译的时候一定要把csparse在EXTERNAL文件中,编译进去. 2)修改CMakeLists.txt文件中的include_directories中的${CPA ...