I am using AngularJS and ui-router and have the following code which catches 404's and loads in a 404 template:
$urlRouterProvider.otherwise(function($injector, $location){
$injector.invoke(['$state', function($state) {
$state.go('404');
}]);
});
It keeps the URL intact instead of redirecting, but shows the 404 template:
.state('404',
{
views: {
'body': {
templateUrl: 'partials/404.html',
}
}
});
Normally it would redirect to the root state with: $urlRouterProvider.otherwise('/');
However when HTML5 mode is turned off and the user visits the root URL e.g. http://www.domain.com/app/
it loads the 404 state instead of redirecting to http://www.domain.com/app/#/
How can I keep the 404 state code above, but have it redirect to the hashbang when accessing the initial page? So effectively only have the 404 load if the request is anything other than the home page?
I can't use the $stateNotFound
or $stateChangeSuccess
and need a way to check if it's a home page request within the actual config setup itself that can toggle between the /
and the state.404
within the otherwise statement.
So something along the lines of (which does seem to work).
$urlRouterProvider.otherwise(function($injector, $location){
$injector.invoke(['$state', function($state) {
if( $location.$$path == '')
$state.go('home'); // redirect to /#/
else
$state.go('404'); // else go to 404 state
}]);
});
But is there a better way to handle this?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With