2015-06-22 38 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 –