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

前端 未结 12 1253
花落未央
花落未央 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:48

    I would additionally suggest a 4th option as a better alternative to the proposed options by @zbynour.

    Use $rootScope.$emit rather than $rootScope.$broadcast regardless of the relationship between trasmitting and receiving controller. That way, the event remains within the set of $rootScope.$$listeners whereas with $rootScope.$broadcast the event propagates to all children scopes, most of which will probably not be listeners of that event anyway. And of course in the receiving controller's end you just use $rootScope.$on.

    For this option you must remember to destroy the controller's rootScope listeners:

    var unbindEventHandler = $rootScope.$on('myEvent', myHandler);
    $scope.$on('$destroy', function () {
      unbindEventHandler();
    });
    

提交回复
热议问题