Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify a default state in AngularJS ui-router module

This is what I'm trying to achieve: When the user enters a URL that is not matched by any of the URL patterns of the states configured in the $stateProvider, the state should be set to a default state that is named for instance 'notFound'. Entering this state must leave the URL untouched, so the user has the chance to correct it. This is why I'm not using $urlRouterProvider.otherwise().

Currently I'm working with the following workaround: In my main controller I check if

$state.current.name == ''

If this is the case, I set the 'notFound' state.

$state.go('notFound', {}, { location: false });

However, it seems a bit like a hack because I assume there is a way to configure all of this in module.config() but I don't know how. Any ideas on this?

like image 491
lex82 Avatar asked Feb 25 '26 11:02

lex82


1 Answers

I found the solution myself: It is possible to use regular expressions for parameters in the URL. So you can define a "catch-all" state as the last state registered in the $stateProvider like this:

$stateProvider.state('notFound', {
    url: '{path:.*}',
    templateUrl: '/notFound.html'
});

If no other URL pattern matches, this state will be selected and the complete path can be accessed via $stateParams.path.

like image 153
lex82 Avatar answered Mar 02 '26 06:03

lex82



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!