<!DOCTYPE html>
<html ng-app="my_app">
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module("my_app", []);
app.controller('div_child1', function($scope) {
$scope.my_broadcast = function() {
var data = {
controller_name: 'div_child1',
msg: '广播'
}
// $emit只能向parent controller广播event与data
// $broadcast只能向child controller广播event与data
$scope.$emit("from_child1_to_main", data);
$scope.$broadcast("from_child1_to_grandchild1", data);
}
});
app.controller('div_main', function($scope) {
//$on用于截获来自子级(div_child1)作用域的事件
$scope.$on("from_child1_to_main", function(event, data) {
console.log('div_main');
console.log(JSON.stringify(data));
});
});
app.controller('div_grandchild1', function($scope) {
//$on用于截获来自父级(div_child1)作用域的事件
$scope.$on("from_child1_to_grandchild1", function(event, data) {
console.log('div_grandchild1');
console.log(JSON.stringify(data));
});
});
</script>
</head>
<body>
<div ng-controller="div_main">
<div ng-controller="div_child1">
<button ng-click="my_broadcast();">广播</button>
<div ng-controller="div_grandchild1">
</div>
</div>
</div>
</body>
</html>