Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load 404 state with AngularJS Router

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.

like image 751
Cameron Avatar asked Mar 24 '16 14:03

Cameron


1 Answers

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?

like image 130
Cameron Avatar answered Nov 09 '22 11:11

Cameron