javascript Angularjs $broadcast 一次,$on 两次

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30968948/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:01:45  来源:igfitidea点击:

Angularjs $broadcast once, $on twice

javascriptangularjsangularjs-scopeevent-listenerangular-broadcast

提问by Shai M.

It sends $broadcast once from the rootScope, but the listener ($on) gets called twice.

它从 rootScope 发送一次 $broadcast,但监听器 ($on) 被调用两次。

The listener is in a controller and it uses $rootScope.$oninstead of $scope.$on. Has someone had this problem?

侦听器位于控制器中,它使用$rootScope.$on而不是$scope.$on. 有人遇到过这个问题吗?

edit

编辑

rootScope:

根范围:

$rootScope.$broadcast('menuActivateAction' + item.event_name_postfix, item.event_args);

other Controller:

其他控制器:

$rootScope.$on('menuActivateActionPublish', function(event) {});

回答by Tomas

Since you register your $on listener on $rootScope, it doesn't get destroyed with the controller and next time you init the controller it gets created again.

由于您在 $rootScope 上注册了 $on 侦听器,因此它不会被控制器销毁,下次您初始化控制器时,它会再次创建。

You should create your listener on controller scope

您应该在控制器范围内创建您的侦听器

$scope.$on('menuActivateActionPublish', function(event) {});

回答by que1326

Be careful you avoid two instances of the controller means two event listeners, which means the method gets executed twice !! ( example: using twice 'ng-controller' )

小心你避免控制器的两个实例意味着两个事件监听器,这意味着该方法被执行两次!!(例如:使用两次 'ng-controller' )

回答by Jo?o Otero

To complement que1326 answer, as an example, if you are using ui-router and have something like

为了补充 que1326 的答案,例如,如果您使用 ui-router 并且有类似的东西

.state('app.yourpage', {
            url:'yourPage',
            views: {
                'content@': {
                    templateUrl : 'views/yourPage.html',
                    controller  : 'YourController'
                }
            }
        })

and in yourPage.html you have a ng-controller="YourController as Ctrl", then you are creating 2 instances of the controller: 1 instance is created by the state configuration and another one in your html.

在 yourPage.html 中,您有一个ng-controller="YourController as Ctrl",然后您正在创建控制器的 2 个实例:1 个实例由状态配置创建,另一个在您的 html 中。

回答by CommandoScorch

The only solution I could get to work was to create the listener inside the $viewContentLoaded event:

我可以开始工作的唯一解决方案是在 $viewContentLoaded 事件中创建侦听器:

$scope.$on('$viewContentLoaded', function() {
  //Put your listener(s) in here
  $scope.$on('menuActivateActionPublish', function(event) {});
});