首先,對$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看到
$scope
然后控制器3$scope
- 發射2-將由控制器2看到
$scope
然后$rootScope
- 廣播3-只會被控制器3看到
$scope
- 發射3-將由控制器3看到
$scope
,主計長2$scope
然后$rootScope
- 廣播根-將被看到
$rootScope
和$scope
所有控制器(1,2,然后3) - 發出根-將僅由
$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');
});}]);