首页 > 解决方案 > AngularJS Route:为同一路由设置多个参数值

问题描述

我想知道AngularJS是否可以做这样的事情:

我目前有一个带有第一个参数的路由,称为“资源”,可以是“设备”或“组”。还有一个名为“id”的参数,但这并不重要。使用以下代码,路由接受任何内容作为第一个参数:

.when("/templates/:resource/:id", {
            templateUrl: "/templates/views/navigation/templates.html",
            controller: 'ctrlTemplates',
            tab: "templates",
        })

如果第一个参数的值是“设备”或“组”,它会让我检查控制器。如果可能的话,我想摆脱这个验证部分而不创建两条路线:

.when("/templates/group/:id", {
                templateUrl: "/templates/views/navigation/templates.html",
                controller: 'ctrlTemplates',
                tab: "templates",
            })
.when("/templates/device/:id", {
                templateUrl: "/templates/views/navigation/templates.html",
                controller: 'ctrlTemplates',
                tab: "templates",
            })

所以我的问题是,是否有可能使用一条路线来拥有多个网址?例如这样的事情:

.when("/templates/('device'|'group')/:id", {
            templateUrl: "/templates/views/navigation/templates.html",
            controller: 'ctrlTemplates',
            tab: "templates",
        })

所以我以后不必自己在控制器中检查参数的值

if([('group', 'device'].includes($routeParams.resource))...

你知道这是否可能吗?或者类似的方法来做到这一点?

此致,

标签: angularjs

解决方案


你不能做你想做的事。如果您想使用 ui-router,您可以将其关闭,但 AngularJS ngRoute 无法让您使用正则表达式或将路由参数绑定到类型。如果您愿意切换到 ui-router,我可以给您一个示例,说明如何做您想做的事情。


推荐阅读