$scope.$emit and .$broadcast AngularJS

首先,$emit和$broadcast都是针对$scope而言的。

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:

以下是Angularjs在不同controller之间共享数据,传播事件的几种基本的情况:

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

 

以上几种示例就能解决不同controller之间共享数据的问题。

不过广播容易造成效率低下的问题,所以尽量选取一个接收者少的方向广播。

About 智足者富

http://chenpeng.info

发表评论

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

您可以使用这些HTML标签和属性:

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