AngularJS ui路由器强制参数

时间:2016-06-10 23:06:35

标签: angularjs angular-ui-router

根据文档,angularjs ui-router url参数默认是可选的。那么有没有办法创建强制参数?就像参数丢失或为null时一样,它不会进入页面?

希望你能帮助我。

由于

2 个答案:

答案 0 :(得分:5)

使用UI路由器resolve检查路由参数是否缺失。

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

答案 1 :(得分:2)

以上回答表示错误使用解决方案,即使注释,代码缩小时也会失败。 Look at this issue我花了很多时间来调试这个,因为ui-router@0.4.2不会警告你,决心应该是对象。

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

如果您需要缩小,ngAnnotate