我搜索了很多,但找不到解決方案: 我是AngularJS的新手,我使用Ionic與Firebase來創建應用。我想阻止來自未認證的用戶的意見。所以當用戶點擊一個沒有驗證的視圖時,應該彈出並將視圖重定向到主頁。AngularJS - 事件偵聽器發射兩次
的代碼是這樣的:
myApp.controller('AppCtrl', ['$scope','$ionicModal', $state,...,
function($scope, $ionicModal, $state,...) {
// Create the login modal that we will use later
$ionicModal.fromTemplateUrl('templates/login.html', {
scope: $scope
}).then(function(modal) {
$scope.modalLogin = modal;
});
// Open the login modal
$scope.login = function() {
if(!$scope.modalLogin.isShown()){
$scope.modalLogin.show();
}
};
/*** Verify Authentication - This is the problematic part... ***/
$scope.$on("$stateChangeStart",
function(event, toState, toParams, fromState, fromParams){
var auth = firebase.auth();
if (toState.views.menuContent.authenticate && auth.currentUser === null){
event.preventDefault();
// User isn’t authenticated
if(fromState.name != "app.home"){
$state.go("app.home");
}
if(!$scope.modalLogin.isShown()){
$scope.login();
}
}
else{
return;
}
});
}]);
的事情是,無論我做什麼了$scope.$on("$stateChangeStart",)
回調函數會觸發兩次。我檢查了一倍控制器聲明,我刪除了$scope.login()
功能,即使事件偵聽器是空,將觸發了兩次:
//Verify Authentication
$scope.$on("$stateChangeStart",
function(event, toState, toParams, fromState, fromParams){
console.log('This fires twice...');
}
有什麼想法?我新來angularJS所以也許這是非常簡單的解決方案,但我找不到它。
在此先感謝。
在您的使用情況下,如果要阻止未認證用戶,你所使用AngularFire更好,庫中有相關功能的要求, https://github.com/firebase/angularfire/blob/master/docs/guide/user-auth.md#authenticating-with-routers – srijanshukla
@srijanshukla感謝您的評論。實際上,我的第一個想法(我認爲是正確的做法)是通過使用$ rootScope的應用程序模塊上的'.run'完成的。但是,我所有的函數都與控制器中的$ scope有關(如上所示),我不知道如何從$ rootScope中使用它們。我是angularJS的初學者,對我來說全新的。我遵循教程,它使用控制器內的$ scope來調用身份驗證服務,模態登錄,註銷等...因此,當使用$ rootScope運行時,我無法在用戶更改路由時觸發模式。 –