I'd like my app to send non-logged in users to a login page. Based on a popular answer here, the app watches for routeChangeStart, like this:
$rootScope.$on("$routeChangeStart", function(event, next, current) {
if ($rootScope.currentUser === null) {
var allowPublic = ["partials/logIn.html", "partials/start.html"];
var allowed = _.contains(allowPublic, next.templateUrl);
if (!allowed) {
$location.path("/logIn").replace();
}
}
});
This logic runs correctly, except that changing $location.path doesn't work. The address bar in the browser changes to /logIn, but the view still shows the non-permitted partial. Does anybody have an idea why?
My routes are setup like this:
$routeProvider.when('/start', {templateUrl: 'partials/start.html', controller: 'StartController'});
$routeProvider.when('/logIn', {templateUrl: 'partials/logIn.html', controller: 'LogInController'});
$routeProvider.when('/restricted', {templateUrl: 'partials/restricted.html', controller: 'RestrictedController'});
The start page controller sometimes tries to navigate to the restricted page, like this:
// in StartController
$scope.pressedButton = function() {
$location.path('/restricted');
// I'd like to catch this and redirect using the previous logic if user is not logged in
};