Using angular-ui-router, How can I use the otherwise method on $stateProvider or how can I use it at all ?


Solution 1:

You can't use only $stateProvider.

You need to inject $urlRouterProvider and create a code similar to:

$urlRouterProvider.otherwise('/otherwise');

The /otherwise url must be defined on a state as usual:

 $stateProvider
    .state("otherwise", { url : '/otherwise'...})

See this link where ksperling explains

Solution 2:

You can with $stateProvider using the catch all syntax ("*path"). You just need to add a state config at the bottom of your list like the following one:

$stateProvider.state("otherwise", {
    url: "*path",
    templateUrl: "views/error-not-found.html"
});

All the options are explained in https://github.com/angular-ui/ui-router/wiki/URL-Routing#regex-parameters.

The nice thing of this option, as opposed to $urlRouterProvider.otherwise(...), is that you 're not forced to a location change.

Solution 3:

You can also manually inject $state into the otherwise function, which you can then navigate to a non-url state. This has the benefit of the browser not changing the addressbar, which is helpful for handling going back to a previous page.

    $urlRouterProvider.otherwise(function ($injector, $location) {
        var $state = $injector.get('$state');

        $state.go('defaultLayout.error', {
            title: "Page not found",
            message: 'Could not find a state associated with url "'+$location.$$url+'"'
        });
    });

Solution 4:

I just want to chime in on the great answers that are already provided. The latest version of @uirouter/angularjs marked the class UrlRouterProvider as deprecated. They now recommend using UrlService instead. You can achieve the same result with the following modification:

$urlService.rules.otherwise('/defaultState');

Additional methods: https://ui-router.github.io/ng1/docs/1.0.16/interfaces/url.urlrulesapi.html