javascript Angular UI-Router 一种状态下的更多可选参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30225424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:55:04  来源:igfitidea点击:

Angular UI-Router more Optional Parameters in one State

javascriptangularjsangular-ui-routerangular-ui

提问by G. Deward

How can I allow optional parameters to my routes without using a query string and only using one route name? I am currently specifying each route FIVE TIMES to allow for any combination of parts:

如何在不使用查询字符串且仅使用一个路由名称的情况下允许我的路由使用可选参数?我目前正在指定每条路线五次以允许部件的任何组合:

All parts must be optional. Route must resolve any variation.

所有部件都必须是可选的。路线必须解决任何变化。

.state("login", { url: "/login", templateUrl: "login.html", params: { a: null, b: null, c: null, d: null } })
.state("loginA", { url: "/login/:a", templateUrl: "login.html", params: { b: null, c: null, d: null } })
.state("loginAB", { url: "/login/:a/:b", templateUrl: "login.html", params: { c: null, d: null } })
.state("loginABC", { url: "/login/:a/:b/:c", templateUrl: "login.html", params: { d: null } })
.state("loginABCD", { url: "/login/:a/:b/:c/:d", templateUrl: "login.html" })

There MUST be an easier / cleaner / less ugly way.

必须有一种更简单/更清洁/不那么丑陋的方式。

回答by Fred Lackey

Short answer....

简短的回答....

.state('login', {
    url: '/login/:a/:b/:c/:d',
    templateUrl: 'views/login.html',
    controller: 'LoginCtrl',
    params: {
        a: { squash: true, value: null },
        b: { squash: true, value: null },
        c: { squash: true, value: null },
        d: { squash: true, value: null },
    }
})

回答by Radim K?hler

There is a working plunker

一个工作plunker

Solution here could be of two types. The first is really very dynamic. The second is working as needed, a bit more rigid, but profiting from UI-Routerbuilt-in features.

这里的解决方案可能有两种类型。第一个真的非常有活力。第二个是根据需要工作,有点严格,但可以从UI-Router内置功能中受益。

I. Dynamic approach

一、动态方法

Let's observe the first, which is interesting (but maybe too much complicated in our scenario). It is very similar to this Q & A

让我们观察第一个,这很有趣(但在我们的场景中可能太复杂了)。和这个问答很相似

Recursive ui router nested views

递归 ui 路由器嵌套视图

We try to solve the urlwhich contains unknown amount of folders*(directories)* names:

我们尝试解决包含未知数量的文件夹*(目录)*名称的网址

<a href="#/files/Folder1">
<a href="#/files/Folder1/SubFolder1/">
<a href="#/files/Folder1/SubFolder1/SubFolderA">

State could be define like this:

状态可以这样定义:

.state('files', {
  url: '/files/{folderPath:[a-zA-Z0-9/]*}',
  templateUrl: 'tpl.files.html',
  ...

And that will lead to one param folderPathwith the complete folder path.

这将导致一个folderPath带有完整文件夹路径的参数。

In case we would like to solve our scenario (handle exactly three params)we could extend stuff like this

如果我们想解决我们的场景(正好处理三个参数),我们可以扩展这样的东西

Controller for File handling:

文件处理控制器:

.controller('FileCtrl', function($scope, a, b, c) {
    $scope.paramA = a; 
    $scope.paramB = b; 
    $scope.paramC = c; 
})

State definition using resolver:

使用解析器的状态定义:

// helper method
var findParams = function($stateParams, position) {
   var parts = $stateParams.folderPath.split('/')
   var result = parts.length >= position ? parts[position] : null;
   return result;
  }

...

// state calls resolver to parse params and pass them into controller
.state('files', {
    url: '/files/{folderPath:[a-zA-Z0-9/]*}',
    templateUrl: 'tpl.files.html',
    controller: 'FileCtrl',
    resolve: {
        a : ['$stateParams', function($stateParams) {return findParams($stateParams, 0)}],
        b : ['$stateParams', function($stateParams) {return findParams($stateParams, 1)}],
        c : ['$stateParams', function($stateParams) {return findParams($stateParams, 2)}],
    }
 })

II. UI-Router built-in feature params : {}

二、UI-Router 内置功能params : {}

The second scenario, is in fact very very simple. It uses UI-Routerbuilt in feature: params : {}. Check its documentation here:

第二种情况,其实非常非常简单。它使用UI-Router内置功能:params : {}. 在此处查看其文档:

http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$stateProvider

http://angular-ui.github.io/ui-router/site/#/api/ui.router.state.$stateProvider

This would be our state definition:

这将是我们的状态定义:

.state('login', {
    url: '/login/:a/:b/:c',
    templateUrl: 'tpl.login.html',
    controller: 'LoginCtrl',
    params: {
        a: {squash: true, value: null},
        b: {squash: true, value: null},
        c: {squash: true, value: null},
    }
})

And all these links will work as well:

所有这些链接也将起作用:

<a href="#/login">
<a href="#/login/ValueA">
<a href="#/login/ValueA/ValueB">
<a href="#/login/ValueA/ValueB/ValueC">

And what was the trick:

诀窍是什么:

squash- {bool|string=}: squash configures how a default parameter value is represented in the URL when the current parameter value is the same as the default value. If squash is not set, it uses the configured default squash policy.

squash- {bool|string=}: squash 配置当当前参数值与默认值相同时,如何在 URL 中表示默认参数值。如果未设置壁球,则使用配置的默认壁球策略。

Check it in action here

这里检查它的行动

回答by Nick A. Watts

Another simple way to do this is to just set a default value for the parameter, like this:

另一种简单的方法是为参数设置一个默认值,如下所示:

params: {
  thing1: ""
}

According to the Angular UI Router docs, setting a default value automatically makes the parameter optional.

根据 Angular UI Router docs,设置默认值会自动使参数成为可选的。

回答by nairys

You can pass optional parameters using ui-sref. You can then access them in your controller using the $stateParams service. Parameters that don't get passed would just remain null.

您可以使用ui-sref传递可选参数。然后您可以使用 $stateParams 服务在您的控制器中访问它们。未通过的参数将保持为空。

.state("loginABCD", 
  { url: "/login/:a/:b/:c/:d",
    templateUrl: "login.html"
    controller: function($stateParams) {
      console.log($stateParams.a + $stateParams.b);
      }
  })