将 url 路径与 $urlRouterProvider.when() 中的正则表达式匹配路径、正则表达式、url、when

2023-09-06 08:57:28 作者:柠檬酱~^o^~

基于 angular ui-router wiki (https:///github.com/angular-ui/ui-router/wiki/URL-Routing#urlrouterprovider)应该可以使用正则表达式来匹配传入路径.我如何表达正则表达式以匹配以下重定向规则:

Based on the angular ui-router wiki (https://github.com/angular-ui/ui-router/wiki/URL-Routing#urlrouterprovider) it should be possible to use regex for matching the incoming path. How could I express regex to match following redirection rules:

$urlRouterProvider
  .when('', '/events')
  .when('/', '/events')
  .when('/:eventName', '/events/:eventName')
  .when('/results', '/events/results')

测试示例:

localhost => localhost/#/events
localhost/ => localhost/#/events
localhost/myEvent => localhost/#/events/myEvent
localhost/results => localhost/#/events/results
localhost/#/events => localhost/#/events
localhost/#/results => localhost/#/results

推荐答案

我找到了答案.when() 语句的顺序和状态定义很重要.

I found the answer. Order of the when() statements and the state definition is important.

这行得通:

$urlRouterProvider
    .when('', '/events')
    .when('/', '/events')
    .when('/results', '/events/results')
$stateProvider
    .state('events', {
    ......
    }
$urlRouterProvider // This needs to be at the end to match all other matches
    .when('/:eventName', '/events/:eventName')