首先,对$on()
、$broadcast()
和 $emit() 的
简短描述:
-
.$on(name, listener)
- 通过给定的给定事件侦听特定事件name
-
.$broadcast(name, args)
- 通过所有儿童向下广播活动$scope
-
.$emit(name, args)
- 向所有父级(包括$scope
$rootScope
基于以下 HTML(请参阅此处的完整示例):
<div ng-controller="Controller1">
<button ng-click="broadcast()">Broadcast 1</button>
<button ng-click="emit()">Emit 1</button>
</div>
<div ng-controller="Controller2">
<button ng-click="broadcast()">Broadcast 2</button>
<button ng-click="emit()">Emit 2</button>
<div ng-controller="Controller3">
<button ng-click="broadcast()">Broadcast 3</button>
<button ng-click="emit()">Emit 3</button>
<br>
<button ng-click="broadcastRoot()">Broadcast Root</button>
<button ng-click="emitRoot()">Emit Root</button>
</div>
</div>
触发的事件将按如下方式遍历:$scopes
- 广播 1 - 仅由控制器 1 看到
$scope
- 发出 1 - 控制器 1 将看到,然后
$scope
$rootScope
- 广播 2 - 控制器 2 和控制器 3 将看到
$scope
$scope
- 发出 2 - 控制器 2 将看到,然后
$scope
$rootScope
- 广播 3 - 仅由控制器 3 看到
$scope
- 发出 3 - 控制器 3、控制器 2 将看到
$scope
$scope
$rootScope
- 广播根 - 所有控制器(1、2 和 3)都将看到
$rootScope
$scope
- 发出根 - 只会被看到
$rootScope
JavaScript来触发事件(同样,你可以在这里看到一个工作示例):
app.controller('Controller1', ['$scope', '$rootScope', function($scope, $rootScope){
$scope.broadcastAndEmit = function(){
// This will be seen by Controller 1 $scope and all children $scopes
$scope.$broadcast('eventX', {data: '$scope.broadcast'});
// Because this event is fired as an emit (goes up) on the $rootScope,
// only the $rootScope will see it
$rootScope.$emit('eventX', {data: '$rootScope.emit'});
};
$scope.emit = function(){
// Controller 1 $scope, and all parent $scopes (including $rootScope)
// will see this event
$scope.$emit('eventX', {data: '$scope.emit'});
};
$scope.$on('eventX', function(ev, args){
console.log('eventX found on Controller1 $scope');
});
$rootScope.$on('eventX', function(ev, args){
console.log('eventX found on $rootScope');
});
}]);