2016-06-10 115 views
4

根據文檔,angularjs ui-router url參數默認是可選的。那麼有沒有辦法創建強制參數?就像參數丟失或爲空時不會進入頁面一樣?AngularJS ui路由器強制性參數

希望你能幫助我。

感謝

+0

爲什麼不「如果(typeof運算PARAM === '未定義'),然後重定向? – user3791775

+0

或之前在您的模板,只是不顯示鏈接? – user3791775

+0

這不符合我的觀點。此外,我不能在我的控制器上做到這一點,有沒有辦法在聲明狀態時做到這一點? – Jed

回答

5

使用UI路由器resolve檢查路線PARAMS丟失。

//Example of a single route 
.state('dashboard', { 
    url: '/dashboard/:userId', 
    templateUrl: 'dashboard.html', 
    controller: 'DashboardController', 
    resolve: function($stateParams, $location){ 

    //Check if url parameter is missing. 
    if ($stateParams.userId === undefined) { 
     //Do something such as navigating to a different page. 
     $location.path('/somewhere/else'); 
    } 
    } 
}) 
+0

腳本縮小時不起作用。你有什麼主意嗎? – Jed

+0

這並不好。道歉。嘗試刪除包裝解析函數的[]。 – Gregg

+1

爲了將來的參考,我沒有去除[],而是AngularJS希望它成爲的方式: 'resolve:['$ stateParams','$ location',function($ stateParams,$ location){ // body here }]' – Jed

2

以上回答prasents 決心的不正確使用時,如果註釋的代碼,甚至是精縮會失敗。 Look at this issue我花了很多時間調試它,因爲[email protected]不會警告您應該反對解決方案。

resolve: { 
    somekey: function($stateParams, $location){ 

     //Check if url parameter is missing. 
     if ($stateParams.userId === undefined) { 
      //Do something such as navigating to a different page. 
      $location.path('/somewhere/else'); 
    } 
} 

如果您需要縮小,​​

+0

您缺少一個結束括號。 – sfs