I have this code:
var app = angular.module('myApp', ['ionic']);
app.config(function($stateProvider) {
$stateProvider
.state('login', {
url: '/',
templateUrl: 'login.html',
controller: 'loginController'
})
.state('home', {
url: '/home',
templateUrl: 'home.html',
controller: 'homeController'
});
});
$urlRouterProvider.otherwise('/');
How can I add a condition to state provider to verify if localstorage.token exist. If yes go to home else go to login
Now, I am going all the time on login state and there (loginController) I verify if I have or not a token on localstorage. I'm not satisfied with my version... that's why I want to improve it
In app.run you can add your logic; this will fire on page-load and on refresh.
.run(function ($state) {
if(localStorage.token) $state.go('home');
else $state.go('login');
})
I would recommend setting home as your default route and performing a redirect if there is no token. So this would be your default route:
$urlRouterProvider.otherwise('/home');
And you would redirect if there is no token. You can do that by watching for the $locationChangeStart event in your run block:
.run(function ($rootScope, $state) {
$rootScope.on('$locationChangeStart', function(event, next, current) {
// check for the user's token and that we aren't going to the login view
if(!localStorage.token && next.templateUrl != 'login.html'){
// go to the login view
$state.go('login');
}
}
})
This has the added benefit of restricting the user to the login view if they have not authenticated.