$on and $broadcast in angular

前端 未结 4 2195
庸人自扰
庸人自扰 2020-11-22 15:08

I have a footerController and codeScannerController with different views.

angular.module(\'myApp\').controller(\'footerController\', [\"$scope\", function($s         


        
4条回答
  •  鱼传尺愫
    2020-11-22 15:16

    First, a short description of $on(), $broadcast() and $emit():

    • .$on(name, listener) - Listens for a specific event by a given name
    • .$broadcast(name, args) - Broadcast an event down through the $scope of all children
    • .$emit(name, args) - Emit an event up the $scope hierarchy to all parents, including the $rootScope

    Based on the following HTML (see full example here):


    The fired events will traverse the $scopes as follows:

    • Broadcast 1 - Will only be seen by Controller 1 $scope
    • Emit 1 - Will be seen by Controller 1 $scope then $rootScope
    • Broadcast 2 - Will be seen by Controller 2 $scope then Controller 3 $scope
    • Emit 2 - Will be seen by Controller 2 $scope then $rootScope
    • Broadcast 3 - Will only be seen by Controller 3 $scope
    • Emit 3 - Will be seen by Controller 3 $scope, Controller 2 $scope then $rootScope
    • Broadcast Root - Will be seen by $rootScope and $scope of all the Controllers (1, 2 then 3)
    • Emit Root - Will only be seen by $rootScope

    JavaScript to trigger events (again, you can see a working example here):

    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');
        });
    }]);
    

提交回复
热议问题