Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
115
rated 0 times [  116] [ 1]  / answers: 1 / hits: 17048  / 11 Years ago, wed, october 30, 2013, 12:00:00

In my AngularJS application I'm redirecting the route to a specific page when the user isn't logged. To do that I'm using a variable on $rootScope.



Now I would like to prevent the browser's back button when the user is logged. I would like to redirect it to a specific page (the registration view). The problem is I don't know if there's a back button event.



My code is:



 angular.module('myApp',[...]
//Route configurations
}])
.run(function($rootScope, $location){
$rootScope.$on('$routeChangeStart', function(event, next, current){
if(!$rootScope.loggedUser) {
$location.path('/register');
}
});
$rootScope.$on('$locationChangeStart', function(event, next, current){
console.log(Current: + current);
console.log(Next: + next);
});
});


So on $locationChangeStart I would write a pseudocode like:



if (event == backButton){
$location.path('/register');
}


Is it possible?



A naive solution would be writing a function that checks if next and current are in the wrong order, detecting if the user is going back.



There are other solutions? I'm approaching the problem in a wrong way?


More From » angularjs

 Answers
31

I found a solution, which is easier than I thought. I register on a object in $rootScope the actual location and on every location change I check with the new one. In this way I can detect if the user is going back in the history.



angular.module('myApp',[...], {
//Route configurations
}])
.run(function($rootScope, $location) {
$rootScope.$on('$routeChangeStart', function(event, next, current) {
if(!$rootScope.loggedUser) {
$location.path('/register');
}
});

$rootScope.$on('$locationChangeSuccess', function() {
$rootScope.actualLocation = $location.path();
});

$rootScope.$watch(function() { return $location.path() },
function(newLocation, oldLocation) {
if($rootScope.actualLocation == newLocation) {
$location.path('/register');
}
});
});
});

[#74612] Tuesday, October 29, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sabinal

Total Points: 144
Total Questions: 112
Total Answers: 107

Location: Ghana
Member since Mon, Aug 22, 2022
2 Years ago
;