Angular $ rootScope.$ broadcast()事件在控制器中捕获两次 [英] Angular $rootScope.$broadcast() event caught twice in controller

查看:272
本文介绍了Angular $ rootScope.$ broadcast()事件在控制器中捕获两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

点击按钮进行宣传活动:-

Broadcating event on button click :-

$scope.onButtonClick = function(){
    $rootScope.$broadcast('onButtonClick');
}

在另一个控制器中捕获事件:-

And catching event in another controller :-

$rootScope.$on('onButtonClick',function(event){
  alert("catched");
  console.log(event);
});

但是它即使开了一次也抓了两次.为什么会这样?

But it caught twice even though it fired only once. Why is that?

推荐答案

事实证明,由于html中的ng-controller声明以及作为ui-router状态设置的一部分,实例化了多个控制器.

As it turned out the multiple controllers were instantiated due to ng-controller declaration in html and also as part of state setup for ui-router.

解决方案是删除其中一个声明.

The solution is to remove one of the declarations.

这篇关于Angular $ rootScope.$ broadcast()事件在控制器中捕获两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆