96

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

a14m
  • 7,808
  • 8
  • 50
  • 67
Adelin
  • 18,144
  • 26
  • 115
  • 175

6 Answers6

124

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

T J
  • 42,762
  • 13
  • 83
  • 138
Richard Keller
  • 1,596
  • 1
  • 12
  • 9
  • 1
    You can actually use `$stateProvider`. It's less work if you just want to display a template, but not redirect. I prefer @juan-hernandez's answer. – Dennis Hackethal Aug 12 '15 at 06:20
  • does the value passed to `otherwise` (in this case `'/otherwise'`) have to match the name of the state (the first parameter to `.state`) or the value for `url` option? – d512 May 04 '16 at 03:52
  • This is now deprecated - see [answer from @babyburger](https://stackoverflow.com/a/52127305/769137) – Vedran May 29 '19 at 09:20
83

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.

Juan Hernandez
  • 2,376
  • 17
  • 13
  • could you please elaborate: `you're not forced to a location change`? – Kevin Meredith Jun 06 '14 at 16:38
  • 1
    What he means is the url will stay what it was. So if the user goes to `/this/does/not/exist`, then the URL will stay that way in the address bar. The other solution will take you to `/otherwise` – Matt Greer Sep 05 '14 at 15:53
  • I used your solution and it worked (I can keep the url that was not found which is great because I'm using http://luisfarzati.github.io/angulartics/ and this way I can also see navigation to pages that were not found) for cases when the url the user navigates to does not exist. However if I navigate to this url using $state.go('otherwise') inside a controller I lose the url. I navigate explicitly to this state when the user goes to an item's details page and the server returns 404 (for example if the item was deleted). Do you know of a way to fix this? – pcatre Sep 24 '14 at 09:37
  • @pcatre you can use option location=false and the url won't change. Eg. $state.go('otherwise',{},{location:false}) – JakubKnejzlik Aug 25 '15 at 00:37
36

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+'"'
        });
    });
Zak Henry
  • 2,075
  • 2
  • 25
  • 36
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

Babyburger
  • 1,730
  • 3
  • 19
  • 32
3

Ok, the silly moment when you realize that the question you asked is already answered in the first lines of the sample code! Just take a look at the sample code.

       angular.module('sample', ['ui.compat'])
      .config(
        [        '$stateProvider', '$routeProvider', '$urlRouterProvider',
        function ($stateProvider,   $routeProvider,   $urlRouterProvider) {
          $urlRouterProvider
            .when('/c?id', '/contacts/:id')
            .otherwise('/'); // <-- This is what I was looking for ! 


          ....

Take a look here.

Adelin
  • 18,144
  • 26
  • 115
  • 175
0

The accepted answer references angular-route asks about ui-router. The accepted answer uses the "monolithic" $routeProvider, which requires the ngRoute module (whereas ui-router needs the ui.router module)

The highest-rated answer uses $stateProvider instead, and says something like .state("otherwise", { url : '/otherwise'... }), but I can't find any mention of "otherwise" in the documentation it links. However, I see that $stateProvider is mentioned in this answer where it says:

You can't use only $stateProvider. You need to inject $urlRouterProvider

That's where my answer might help you. For me, it was sufficient to use $urlRouterProvider just like this:

 my_module
   .config([
    , '$urlRouterProvider'
    , function(
        , $urlRouterProvider){
            //When the url is empty; i.e. what I consider to be "the default"
            //Then send the user to whatever state is served at the URL '/starting' 
            //(It could say '/default' or any other path you want)
            $urlRouterProvider
                    .when('', '/starting');
                    //...
    }]);

My suggestion is consistent with the ui-router documentation, (this specific revision), where it includes a similar use of the .when(...) method (the first call to the function):

app.config(function($urlRouterProvider){
  // when there is an empty route, redirect to /index   
  $urlRouterProvider.when('', '/index');

  // You can also use regex for the match parameter
  $urlRouterProvider.when(/aspx/i, '/index');
})
Nate Anderson
  • 18,334
  • 18
  • 100
  • 135