1

我搜索了很多,但找不到解决方案: 我是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所以也许这是非常简单的解决方案,但我找不到它。

在此先感谢。

+0

在您的使用情况下,如果要阻止未认证用户,你所使用AngularFire更好,库中有相关功能的要求, https://github.com/firebase/angularfire/blob/master/docs/guide/user-auth.md#authenticating-with-routers – srijanshukla

+0

@srijanshukla感谢您的评论。实际上,我的第一个想法(我认为是正确的做法)是通过使用$ rootScope的应用程序模块上的'.run'完成的。但是,我所有的函数都与控制器中的$ scope有关(如上所示),我不知道如何从$ rootScope中使用它们。我是angularJS的初学者,对我来说全新的。我遵循教程,它使用控制器内的$ scope来调用身份验证服务,模态登录,注销等...因此,当使用$ rootScope运行时,我无法在用户更改路由时触发模式。 –

回答

1

这在过去发生在我身上,问题是因为角度被加载了两次。我已经包括了角色剧本,而离子角色包含了角色剧本。

删除我们自己的角度脚本,让离子处理它是为我解决

+1

谢谢你!它像一个魅力。我花了几个小时。问题是我正在使用angular-bind-html-compile,可能它会调用两次角度。在我调用angularJS两次之前,不知何故,我总是在控制台中发出警告,所以我没有多少打扰。再次感谢! –