Having trouble with redirect in angularJS?
For instance, everything works smoothly when a user logs in. If the user is logged in (information stored in local storage), they are automatically redirected to '/dashboard'.
However, when the user logs out, instead of being redirected elsewhere as intended, it goes to 'http://localhost/ngJS/index.php#'. What am I doing wrong?
The ngJS folder serves as the project root, and index.php contains libraries and code inclusions. The websites are running on a local server called XAMPP.
MainAppMdl.js
var app = angular.module('mainApp', ['ngRoute']);
/*
* Configuration for redirection
* @param {type} $routeProvider
*/
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
//WORKING
.when('/', {resolve: {
"check": function ($location) {
if (localStorage.getItem('usr') &&
localStorage.getItem('usr') !== '0') {
$location.path('/dashboard');
}
}
},templateUrl: 'pages/cover.html'
})
//WORKING LOADING THE CONTROLLER SUCCESSFULLY
.when('/dashboard', {
resolve: {
"check": function ($location) {
if (localStorage.getItem('usr') === '0') {
$location.path('/');
}}},
templateUrl: 'pages/dummy.html',
controller: 'logoutCtrl'
})
.when('/login', {
templateUrl: 'pages/login/login.html',
controller: 'loginCtrl'
})
.when('/logout', {redirectTo: '/'})
.otherwise({redirectTo: '/'});
}]);
LogoutCtrl
app.controller('logoutCtrl', function ($scope, $rootScope, $location, $log)
{
$log.log('logoutCtrl');
$log.log($scope);
$scope.message = $rootScope.message;
$scope.logout = function () {
if (typeof (localStorage) !== 'undefined') {
localStorage.setItem('usr', 0);
// NOT WORKING --------------------- redirect
$location.path('/');
// WORKING AND PRINTING ---------------------
console.log('redirecting!');
}
/* No localstorage support */
else {
alert("Sorry. Localstorage is not supported");
}
};
});
Logout-template.php
<section class="bg-success text-info" id="horizontal-nav-pills" >
<nav>
<ul class="nav nav-pills nav-justified">
<li role="presentation" class="active"><a href="#">Home</a></li>
<li role="presentation"><a href="#/new-report"><span class="glyphicon glyphicon-plus"></span> Report</a></li>
<li role="presentation"><a href="#"><span class="glyphicon glyphicon-chevron-left"></span></a></li>
<li role="presentation"><a href="#"><span class="glyphicon glyphicon-chevron-right"></span></a></li>
<li role="presentation" ><a href="#" ng-click="logout();">Logout</a></li>
</ul>
</nav>
</section>
<!--end horizontal-nav-pills-->