在$ urlRouterProvider.when()中使用正则表达式匹配url路径

时间:2014-04-15 20:51:26

标签: angularjs angular-ui-router

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

$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

1 个答案:

答案 0 :(得分:6)

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

这有效:

$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')