angularjs的事件 $broadcast and $emit and $on

时间:2023-03-08 15:35:56

angularjs的事件 $broadcast and $emit and $on

angularjs的事件 $broadcast and $emit and $on

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body ng-app="search">
<div ng-controller="ParentCtrl">
<div ng-controller="SelfCtrl">
<a class="btn" ng-click="click()">click me</a>
<div ng-controller="ChildCtrl"></div>
</div>
<div ng-controller="BroCtrl"></div>
</div>
<script src="angular.min.js"></script>
<script>
var search = angular.module('search', [])
.controller('ParentCtrl', function($scope) {
$scope.$on('to-child', function(e, d) {
console.log('关我毛事')
})
$scope.$on('to-parent', function(e, d) {
console.log('we are the parent, I got it', d)
})
})
.controller('SelfCtrl', function($scope) {
$scope.click = function () {
$scope.$broadcast('to-child', 'haha') // 向子
$scope.$emit('to-parent', 'hehe') // 向父
}
})
.controller('ChildCtrl', function($scope){
$scope.$on('to-child', function(e, d) {
console.log('I\' the child, I got it', d)
})
$scope.$on('to-parent', function(e, d) {
console.log('关我毛事')
})
})
.controller('BroCtrl', function($scope){
$scope.$on('to-child', function(e, d) {
console.log('关我毛事')
})
$scope.$on('to-parent', function(e, d) {
console.log('关我毛事')
})
})
</script>
</body>
</html>