How to specify default state in u-router module from AngularJS

This is what I am trying to achieve: when a user enters a URL that does not match any of the state URL patterns configured in $stateProvider, the state should be set to the default state, which is named, for example 'notFound'. Entering this state should leave the URL intact, so the user has the opportunity to fix it. That is why I do not use $urlRouterProvider.otherwise().

I am currently working with the following workaround: In my main controller, I check

$state.current.name == ''

If so, I set the state 'notFound'.

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

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

+3
source share
1 answer

I found the solution myself: in the URL you can use regular expressions for parameters. That way, you can define the catch-all state as the last state registered in the $stateProviderfollowing way:

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

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

+3
source

All Articles