lex82
lex82

Reputation: 11297

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?

Upvotes: 3

Views: 2236

Answers (1)

lex82
lex82

Reputation: 11297

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.

Upvotes: 3

Related Questions