AngularJS的$emit和$broadcast实例
$emit和$broadcast使得event、data在controller与view之间的传递变的简单。
- $emit只能向parent controller传递event与data
- $broadcast只能向child controller传递event与data
实例代码:
AngularEvent.html
<!DOCTYPE html>
<html>
<head>
<script src="lib/jquery-1.9.1.js"></script>
<script src="lib/angular.js"></script>
<script type="text/javascript" src="js/emit-broadcast.js"></script>
<style>
.ng-scope {
border: 1px dotted red;
}
</style>
</head>
<body>
<div ng-app="" class="container">
<div ng-controller="EventController" class="span12">
Root scope MyEvent count: {{count}}
<ul>
<li ng-repeat="i in [1]" ng-controller="AbcController">
<button ng-click="$emit('MyEvent')">$emit('MyEvent')</button>
<button ng-click="$broadcast('MyEvent')">$broadcast('MyEvent')</button>
<button ng-click="fireEvent()">fireEvent()</button>
<br>
Middle scope MyEvent count: {{count}}
<ul>
<li ng-repeat="item in [1, 2]" ng-controller="EventController">
- Leaf scope MyEvent count: {{count}}
</li>
</ul>
</li>
</ul>
</div>
</div>
</body>
</html>
emit-broadcast.js
function EventController($scope) { $scope.count = 0; $scope.$on('MyEvent', function() { $scope.count++; }); } function AbcController($scope) { $scope.fireEvent = function() { $scope.$emit('MyEvent'); $scope.$broadcast('MyEvent'); }; }
运行效果:
刚打开页面
点击“$emit('MyEvent')”按钮,发现Root和Middle scope下的count变化了,每点击一次加1。
点击“$broadcast('MyEvent')”按钮,发现Leaf scope下的count变化了,每点击一次加1。
点击“fireEvent()”按钮,发现整个scope下的count变化了,每点击一次加1(因为在fireEvent方法中有$emit、$broadcast事件MyEvent)。