如何使用AngularJS UI路由器捕获这个网址,以及可选的参数? [英] How to use AngularJS UI-router capture this URL with an optional parameter?
问题描述
我使用AngularJD UI路由器来捕捉我的网址,并从该网址发送两个参数来我的控制器。这里是我的要求:
I'm using AngularJD ui-router to capture my URL and send two parameters from that URL to my controller. Here are my requirements:
- 第一个参数是一个强制性的整数(
ID
) - 第二个参数是一个可选的字符串(
蛞蝓
) - 这两个参数是由
/
分离 - 我希望它忽略任何一个尾随
/
- The first parameter is a mandatory integer (
id
) - The second parameter is an optional string (
slug
) - The two parameters are separated by a
/
- I want it to ignore any single trailing
/
目前,我这样做是:
$stateProvider.state('mystate',
{
url: '/mystate/{id:int}{slug:(?:/[^/]+)?}',
params: {
slug: {value: null}
},
templateUrl: 'partials/mystate.html',
controller: function($stateParams) {
console.log('$stateParams.id=',$stateParams.id, ' $stateParams.slug=',$stateParams.slug);
}
}
有关网址: mystate / 1
这个正确捕获:
For URL: mystate/1
This correctly captures:
$stateParams.id=1, $stateParams.slug=null
有关网址: mystate / 1 / myslug
这捕获了塞错误的值
:
$stateParams.id=1, $stateParams.slug=/asdad
有关网址: mystate / 1 /
这并不捕获任何
For URL: mystate/1/
This doesn't capture anything.
有关网址: mystate / 1 / myslug /
这并不捕获任何
For URL: mystate/1/myslug/
This doesn't capture anything.
我怎么可以这样写,这样它抓住了正确的网址上述所有四个,但没有通过任何的 /
s到控制器?
How can I write this so that it captures all four of the aforementioned URLs properly but doesn't pass any of the /
s to the controller?
推荐答案
有关可选尾部的斜杠,你需要<一个href=\"https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-make-a-trailing-slash-optional-for-all-routes\"相对=nofollow>设置严格模式为false 在配置块:
For optional trailing slash, you need to set strict mode to false in a config block:
angular.module('yourModule').config(['$urlMatcherFactoryProvider', function($urlMatcherFactoryProvider) {
$urlMatcherFactoryProvider.strictMode(false);
}]);
对于具有可选参数,还有很长的讨论这里。最后,他们建议使用壁球
:
For having optional parameters, there's a long discussion here. At the end, they suggest using squash
:
$stateProvider.state('mystate',
{
url: '/mystate/{id:int}/:slug',
params: {
slug: {value: null, squash: true}
},
templateUrl: 'partials/mystate.html',
controller: ['$stateParams', function($stateParams) {
console.log('$stateParams.id=',$stateParams.id, ' $stateParams.slug=',$stateParams.slug);
}]
}
壁球
具有良好的文档,如果将其设置为true,它忽略从URL参数时,它的默认值。
squash
has good documentation, if you set it to true, it omits the parameter from URL when it has the default value.
这篇关于如何使用AngularJS UI路由器捕获这个网址,以及可选的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!