$scope.$emit and .$broadcast AngularJS


First of all, parent-child scope relation does matter. You have two possibilities to emit some event:

  • $broadcast — dispatches the event downwards to all child scopes. 将事件向下传播到所有子作用域,包括自己。
  • $emit — dispatches the event upwards through the scope hierarchy. 将事件向上传播到所有子作用域,包括自己。

I don’t know anything about your controllers (scopes) relation, but there are several options:


  1. If scope of firstCtrl is parent of the secondCtrl scope, your code should work by replacing $emit by $broadcast in firstCtrl:父controller向下广播,子controller接收

    function firstCtrl($scope){
        $scope.$broadcast('someEvent', [1,2,3]);
    function secondCtrl($scope){
        $scope.$on('someEvent', function(event, mass) {console.log(mass)});
  2. In case there is no parent-child relation between your scopes you can inject $rootScope into the controller and broadcast the event to all child scopes (i.e. also secondCtrl). 平级的controller之间可以借助$rootScope向下广播,兄弟controller接收

    function firstCtrl($rootScope){
        $rootScope.$broadcast('someEvent', [1,2,3]);
  3. Finally, when you need to dispatch the event from child controller to scopes upwards you can use $scope.$emit. If scope of firstCtrl is parent of the secondCtrl scope: 子controller向上广播,父controller接收

    function firstCtrl($scope){
        $scope.$on('someEvent', function(event, data) { console.log(data); });
    function secondCtrl($scope){
        $scope.$emit('someEvent', [1,2,3]);




About 智足者富



电子邮件地址不会被公开。 必填项已用*标注

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>