否则在StateProvider上

时间:2013-05-28 13:46:44

标签: angularjs angular-ui angular-ui-router

使用angular-ui-router,如何使用otherwise method上的$stateProvider或者我该如何使用它?

6 个答案:

答案 0 :(得分:121)

您不能仅使用$stateProvider

您需要注入$urlRouterProvider并创建类似于:

的代码
$urlRouterProvider.otherwise('/otherwise');

必须像往常一样在状态上定义/otherwise网址:

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

请参阅此ksperling explains

的链接

答案 1 :(得分:81)

您可以$stateProvider使用捕获所有语法"*path")。您只需在列表底部添加状态配置,如下所示:

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

https://github.com/angular-ui/ui-router/wiki/URL-Routing#regex-parameters中解释了所有选项。

$urlRouterProvider.otherwise(...)相反,此选项的优点在于您不会被迫进行位置更改。

答案 2 :(得分:34)

您也可以手动将$ state注入其他函数,然后您可以导航到非url状态。这样做的好处是浏览器不会更改地址栏,这有助于处理返回上一页。

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

答案 3 :(得分:3)

好的,当您意识到您提出的问题已在示例代码的第一行中得到解答时,这是一个愚蠢的时刻!只需看看示例代码。

       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.

答案 4 :(得分:2)

我只想听一下已经提供的好答案。 @uirouter/angularjs的最新版本将类UrlRouterProvider标记为已弃用。他们现在建议改为使用UrlService。您可以通过以下修改获得相同的结果:

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

其他方法:https://ui-router.github.io/ng1/docs/1.0.16/interfaces/url.urlrulesapi.html

答案 5 :(得分:0)

accepted answer引用angular-route询问ui-router。接受的答案使用"monolithic" $routeProvider,这需要ngRoute模块(而ui-router需要ui.router模块)

highest-rated answer使用$stateProvider代替.state("otherwise", { url : '/otherwise'... }), 但我无法提及&#34;否则&#34;在documentation it links。但是,我看到$stateProvider被提到in this answer,其中说:

  

您不能仅使用$stateProvider。您需要注入$urlRouterProvider

我的答案可以帮到你。对我来说,使用$urlRouterProvider就足够了:

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

我的建议与ui-router documentation,(this specific revision)一致,其中包含类似使用。when(...)方法(对函数的第一次调用) ):

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');
})
相关问题