AngularJS ui-router otherwise to state instead of url?

All we need is an easy explanation of the problem, so here it is.

I am using AngularJS and ui-router and in my app.js. I have the following line:

$urlRouterProvider.otherwise('/');

However I do not want it to send the user to a URL but instead to a state:

.state('404',
        {
            views: {
                'body': {
                    templateUrl: 'partials/404.html',
                }
            }
        });

Normally I would just do this:

$state.go('404');

How can I do this for the otherwise method?

Note: that my 404 state does not have a URL, so basically it keeps the URL that the user has entered or visited and just changes the template.

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

I think you achieved that with this code

$urlRouterProvider.otherwise(function($injector, $location){
  $injector.invoke(['$state', function($state) {
    $state.go('404');
  }]);
}); 

Method 2

Try This.

$urlRouterProvider.otherwise(function($injector, $location){
    $injector.get('$state').go('404');
});

Method 3

Just a small improvement to @kdlcruz’s answer:

$urlRouterProvider.otherwise(function($injector){
    $injector.invoke(['$state', function($state) {
        $state.go('404', {}, { location: false } );
    }]);
});

By doing that, you still able to keep the incorrect the URL and only state is changed.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply