2016-06-10 128 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