2015-06-22 31 views
0

在app.js我正在使用$ rootScope中的回调函数广播来获取第二个控制器上的方法。AngularJS:如何避免 - 从app.js调用的广播事件被触发两次?

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

在控制器我有监听器:

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

问题是,警报( “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'); 
    }); 
+0

你是否在路线和html中连接两次控制器? –

+0

您是否认为我刚加入问题的路由器?控制器在这里提到,在index.html和ng-init – redrom

+0

好的,你在html中使用'ng-controller'吗? –

回答

1

如果要连接控制器的两倍,它会调用两次。

检查您是否将控制器连接到routes配置文件和html(使用ng-controller),如果连接两次(使用两种方式),请删除一个。

cheerz

+0

我认为,该控制器必须在index.html中定义,如果应该附加到任何模板(视图)应该在路由中定义。从视图中删除ng-controller属性解决了我的问题。 – redrom

+0

umm nope基本上是分配给视图的控制器,它将控制该html内容的行为。如果您有多个视图,那么应该有多个控制器来处理它们,并且您可以在'route'配置中或在视图中定义控制器。 –

+0

这里是关于'ng-controller'的一个很好的解释http://blog.pluralsight.com/angularjs-step-by-step-controllers –