I searched a lot but I couldn't find a solution for my problem: I am new to AngularJS and I am using Ionic with Firebase to create an app. I want to block views from unauthenticated users. So when the user clicks on a view without authentication the Login modal should popup and redirect the view to home.
The code is like this:
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;
}
});
}]);
The thing is that no matter what I do the $scope.$on("$stateChangeStart",) callback function will fire twice. I checked for doubled controller declarations, I removed the $scope.login() function and even if the event listener is empty it is fired twice:
//Verify Authentication
$scope.$on("$stateChangeStart",
function(event, toState, toParams, fromState, fromParams){
console.log('This fires twice...');
}
Any thoughts? I new to angularJS so maybe it's very simple solution, but I couldn't find it.
Thanks in advance.
.runon app module using $rootScope. However, all my functions are related to $scope inside the controller(as you can see above) and I don't know how to use them from $rootScope. I am beginner in angularJS and it's all new to me. I followed a tutorial and it uses $scope inside the controller to call the authentication service, modal Login, logout etc... So when running with $rootScope I couldn't manage to trigger the modal when the user changes routes.