2015-03-30 149 views
0

所以我有這部分應用程序結構,我想要實現的行爲是:我想在用戶嘗試訪問未經授權的路由時觸發一個事件,然後在LoginCtrl上監聽該事件

//First controller in application 
<body data-ng-controller="GatewayCtrl"> 
    <div id="wrapper" data-ui-view="main"></div> 
</body> 

//then I have route which has `LoginCtrl` controller 
$stateProvider 
    .state('login', { 
     url: '/login', 
     views: { 
      'main': { 
       templateUrl: 'login.html', 
       controller: 'LoginCtrl' 
      } 
     } 
    }); 


app.run(['$rootScope', function ($rootScope) { 
    $rootScope.$on('$stateChangeStart', function (event, next) { 
     $rootScope.$broadcast('test-event'); 
    }); 
}]); 


mdm.controller('LoginCtrl', ['$scope', function ($scope) { 
    $scope.$on('test-event', function() { 
     console.log('event'); 
    }); 
}]); 

mdm.controller('CounterCtrl', ['$scope', function ($scope) { 
    $scope.$on('test-event', function() { 
     console.log('event'); 
    }); 
}]); 

現在的問題是,事件被射擊GatewayCtrl控制器,但沒有LoginCtrl

是什麼導致了這個問題,我該如何解決它?

+0

你可以發佈'GatewayCtrl'代碼嗎?也許這是取消事件? – 2015-03-30 19:20:03

回答

0

那麼,這裏發生的事情是角度控制器必須綁定到一個元素或頁面(通過ng-controller屬性或預定義路由 - 在你的情況下「/ login」)。

因此,根據您的示例,LoginCtrl還沒有實例化,因此它無法將監聽器添加到該事件中,甚至更進一步,一旦它被銷燬[控制器],監聽器將會也一樣。所以我不認爲這是最好的策略。

你有幾個選擇這裏: A)有一個根控制器,將整個應用程序總是被實例化,如AppController的這個「監聽器」,和/或 B)使用route.resolves來處理頁面授權,這個鏈接上有一個很好的例子:AngularJS $rootScope.$broadcast not working in app.run;

相關問題