$emit和$broadcast使得event、data在controller与view之间的传递变的简单。
<link href="../bootstrap.css" rel="stylesheet"/>
<script type="text/javascript" src="../jquery.js"></script>
<script type="text/javascript" src="../bootstrap.js"></script>
<script type="text/javascript" src="../angular.js"></script>
<script type="text/javascript" src="emit-broadcast.js"></script>
<style>
.ng-scope {
border: 1px dotted red;
}
</style>
<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>
<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>
$scope.count = 0;
$scope.$on('MyEvent', function() {
$scope.count++;
});
// $scope.count = 0;
$scope.fireEvent = function() {
$scope.$emit('MyEvent');
$scope.$broadcast('MyEvent');
};
- $emit只能向parent controller传递event与data
- $broadcast只能向child controller传递event与data
先看测试代码:
emit-broadcast.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div ng-app="" class="container">
</div>
</body>
</html>
emit-broadcast.js
function EventController($scope) {
}
function AbcController($scope) {
}
*注意resources的location哦,建议使用chrome调试,比较方便