Otherwise on StateProvider

前端 未结 6 1715
粉色の甜心
粉色の甜心 2020-11-27 14:35

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

6条回答
  •  盖世英雄少女心
    2020-11-27 14:55

    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');
    })
    

提交回复
热议问题