簡體   English   中英

如何使用UI-Router定義可選參數而不使用尾部斜杠?

[英]How to define optional parameter using UI-Router without trailing slash as well?

我正在努力將我的Angularjs代碼從ng-router遷移到UI-Router。 在我的ng-router中我有可選參數但是我意識到在ui-router中不支持同樣簡單的方法來支持可選參數。 以下是我現有的ng-router模塊的路由。

//Define routes for view  using ng-router
$routeProvider.
        when('/my-app/home/:userid?', {
            templateUrl: '/templates/partials/home/HomeView.html',
            controller: 'HomeViewController'
        })                   
        .when('/my-app/:productKey/:userid?', {
            templateUrl: '/templates/partials/productpage/ProductPageView.html',
            controller: 'ProductViewController'
        })
        .otherwise({redirectTo: '/my-app/home'});

注意:如果您看到“:userid”參數在這里非常順利地實現為可選。

我嘗試在ui-router中跟隨但是同樣不起作用。 我經歷了很多帖子,建議復制路線。 我真的不想復制,因為它會使代碼變臟。

//Set the default route

$urlRouterProvider.otherwise('/my-app/home');
//Define routes for view   (Please make sure the most matched pattern is define at top)
$stateProvider
        .state('viewallcards', {
            url: '/my-app/home/:userid',
            templateUrl: '/templates/partials/home/HomeView.html',
            controller: 'HomeViewController'
        })
        .state('productpage', {
            url: '/my-app/:productKey/:userid',
            templateUrl: '/templates/partials/productpage/ProductPageView.html',
            controller: 'ProductViewController'
        });

這里/ my-app / home /但是/ my-app / home不起作用。 怎么做也沒有尾隨斜線?

在同一個問題上關注帖子也讓我感到驚訝,知道ui-router不支持這個。 它仍然有效嗎? 請幫忙。

一個工作的例子

我們可以使用params : {} object來完全按照我們的需要定義userid (即准備省略)

在這里查看有關params更多詳情:

Angular ui路由器在沒有URL的狀態之間傳遞數據

  $stateProvider
    .state('viewallcards', {
      url: '/my-app/home/:userid',
      params: { 
        userid: {squash: true, value: null }, // this will make both links below working:
        //         #/my-app/home
        //         #/my-app/home/
      },
      ...
    })
    .state('productpage', {
      url: '/my-app/:productKey/:userid',
      ...
    })

在這里檢查它

默認情況下,UI路由器處於“嚴格模式” - 它區分具有尾部斜杠的路徑和不具有斜杠的路徑。 您可以通過禁用此模式關閉此功能:

當網址包含尾部斜杠時,如何激活我的路由?

在配置塊中將strictMode設置為false:

$urlMatcherFactoryProvider.strictMode(false)

對於舊版本的ui-router,請將此代碼段添加到模塊的配置功能中。 它在$ urlRouterProvider上創建一個規則,該規則將所有缺少尾部斜杠的URL映射到同一個URL,但附加了斜杠。

使用此選項,最好將可選參數定義為home?userid=foo樣式的URL參數home?userid=foo ,並設置您希望在URL中看到的內容。

來自UI-Router的Wiki

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM