Working with $scope.$emit and $scope.$on

前端 未结 12 1238
花落未央
花落未央 2020-11-21 15:22

How can I send my $scope object from one controller to another using .$emit and .$on methods?

function firstCtrl($scop         


        
12条回答
  •  甜味超标
    2020-11-21 15:45

    To send $scope object from one controller to another, I will discuss about $rootScope.$broadcast and $rootScope.$emit here as they are used most.

    Case 1:

    $rootScope.$broadcast:-

    $rootScope.$broadcast('myEvent',$scope.data);//Here `myEvent` is event name
    
    $rootScope.$on('myEvent', function(event, data) {} //listener on `myEvent` event
    

    $rootScope listener are not destroyed automatically. You need to destroy it using $destroy. It is better to use $scope.$on as listeners on $scope are destroyed automatically i.e. as soon as $scope is destroyed.

    $scope.$on('myEvent', function(event, data) {}
    

    Or,

      var customeEventListener = $rootScope.$on('myEvent', function(event, data) {
    
      }
      $scope.$on('$destroy', function() {
            customeEventListener();
      });
    

    Case 2:

    $rootScope.$emit:

       $rootScope.$emit('myEvent',$scope.data);
    
       $rootScope.$on('myEvent', function(event, data) {}//$scope.$on not works
    

    The major difference in $emit and $broadcast is that $rootScope.$emit event must be listened using $rootScope.$on, because the emitted event never comes down through the scope tree..
    In this case also you must destroy the listener as in the case of $broadcast.

    Edit:

    I prefer not to use $rootScope.$broadcast + $scope.$on but use $rootScope.$emit+ $rootScope.$on. The $rootScope.$broadcast + $scope.$on combo can cause serious performance problems. That is because the event will bubble down through all scopes.

    Edit 2:

    The issue addressed in this answer have been resolved in angular.js version 1.2.7. $broadcast now avoids bubbling over unregistered scopes and runs just as fast as $emit.

提交回复
热议问题