angular优秀特性之一–事件传播机制
- $emit方法实现事件从子作用域路径到父作用域
<!DOCTYPE html>
<html lang="en" ng-app="eventModule">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../../angular.min.js"></script>
<style>
.parent{
width: 300px;
height: 300px;
border: 1px solid #000;
}
.child{
width: 100px;
height: 100px;
border: 1px solid #000;
margin: 100px auto;
}
button{
width: 50px;
height: 50px;
}
</style>
</head>
<body>
<div class="parent" ng-controller="ParentCon">
<div class="child" ng-controller="ChildCon">
<button ng-click="postEvent()"></button>
</div>
</div>
<script>
var app=angular.module('eventModule',[]);
app.controller('ParentCon',function ($scope) {
$scope.$on('infoEvent',function (event,data) {
console.log(data)
})
});
app.controller('ChildCon',function ($scope) {
$scope.postEvent=function () {
$scope.$emit('infoEvent',{name:'Jane',age:23})
}
})
</script>
</body>
</html>
$scope.$emit('infoEvent',{name:'Jane',age:23})
$emit()方法第一个参数是事件名称,后面可以传入多个参数,这些参数能被传递到父作用域注册的事件监听器中。
- $broadcast方法实现事件父作用域广播到子作用域中
<!DOCTYPE html>
<html lang="en" ng-app="eventModule">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="../../angular.min.js"></script>
<style>
.parent{
width: 300px;
height: 300px;
border: 1px solid #000;
}
.child{
width: 100px;
height: 100px;
border: 1px solid #000;
margin: 100px auto;
}
button{
width: 50px;
height: 50px;
}
</style>
</head>
<body>
<div class="parent" ng-controller="ParentCon">
<button ng-click="postEvent()"></button>
<div class="child" ng-controller="ChildCon">
</div>
</div>
<script>
var app=angular.module('eventModule',[]);
app.controller('ParentCon',function ($scope) {
$scope.postEvent=function () {
$scope.$broadcast('infoEvent',{name:'Jane',age:23})
};
});
app.controller('ChildCon',function ($scope) {
$scope.$on('infoEvent',function (event,data) {
console.log(data)
})
})
</script>
</body>
</html>
- 作用域对象$on方法详解
$scope.$on('infoEvent',function (event,data) {
console.log(data)
})
$on方法用于注册一个时间监听器,第一个参数监听事件名称,第二个参数监听事件处理方法。
事件处理方法的第一个参数event为事件对象,第二个参数data为调用emit或者broadcast方法传递的数据。