【问题标题】:AngularJS : How to avoid - Broadcast event called from app.js is triggered twice?AngularJS:如何避免 - 从 app.js 调用的广播事件被触发两次?
【发布时间】:2015-06-22 08:53:58
【问题描述】:

在 app.js 中,我使用 $rootScope 上的回调函数广播来获取第二个控制器上的触发方法。

function onSuccess(state) {
          if (state != true) {
          } else {
              $rootScope.$broadcast('proximityCatched', null);
          }
          //console.log('Proximity state: ' + (state ? 'near' : 'far'));
      };

在控制器上我有监听器:

$rootScope.$on('proximityCatched', function () {
            alert("TEST");
        });

问题是 alert("TEST");被触发两次。

我尝试使用 stopPropagation 或在正常范围内使用广播来找到任何可行的解决方案,但没有运气。

我怎样才能以正确的方式做到这一点?

感谢您的建议。

编辑:路由器配置:

.config(function($stateProvider, $urlRouterProvider) {
      $stateProvider
          .state('game', {
              url: "/game",
              templateUrl: "templates/game.html",
              controller: "GameCtrl"
          })
          .state('home', {
              url: "/home",
              templateUrl: "templates/home.html",
              controller: "HomeCtrl"
          })
        // if none of the above states are matched, use this as the fallback
        $urlRouterProvider.otherwise('/home');
    });

【问题讨论】:

  • 您是否在路由和 html 中附加了两次控制器?
  • 你认为我刚刚添加的路由器有问题吗?这里提到了控制器,在 index.html 和 ng-init
  • 好的,你在 html 中使用 ng-controller 吗?
  • 是的,我应该删除它吗?
  • 是的,这就是它调用两次的原因

标签: javascript android jquery angularjs


【解决方案1】:

如果您连接控制器两次,它将调用两次。

检查您是否在routes 配置和html 中附加了控制器(通过使用ng-controller),如果您附加了两次(使用两种方式),请删除一个。

欢呼

【讨论】:

  • 我认为,该控制器必须在 index.html 中定义,如果应该附加到任何模板(视图)也应该在路由中定义。从视图中删除 ng-controller 属性解决了我的问题。
  • 嗯,不,基本上是分配给视图的控制器,它将控制该 html 内容的行为。如果您有多个视图,那么应该有多个控制器来处理它们,您可以在route config 或视图中定义控制器。
  • 这里有一个关于ng-controllerblog.pluralsight.com/angularjs-step-by-step-controllers的很好的解释
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-16
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多