如何使用 AngularJS UI-router 使用可选参数捕获此 URL? [英] How to use AngularJS UI-router capture this URL with an optional parameter?

查看:24
本文介绍了如何使用 AngularJS UI-router 使用可选参数捕获此 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 AngularJD ui-router 来捕获我的 URL 并将两个参数从该 URL 发送到我的控制器.这是我的要求:

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)
  • 第二个参数是一个可选字符串(slug)
  • 两个参数用/
  • 分隔
  • 我希望它忽略任何单个尾随 /

目前,我正在这样做:

$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);
    }
  }

对于 URL:mystate/1 这正确捕获:

For URL: mystate/1 This correctly captures:

$stateParams.id=1, $stateParams.slug=null

对于 URL:mystate/1/myslug 这捕获了 slug 的错误值:

For URL: mystate/1/myslug This captures the wrong value for slug:

$stateParams.id=1, $stateParams.slug=/asdad

对于 URL:mystate/1/ 这不会捕获任何内容.

For URL: mystate/1/ This doesn't capture anything.

对于 URL:mystate/1/myslug/ 这不会捕获任何内容.

For URL: mystate/1/myslug/ This doesn't capture anything.

我该如何编写它才能正确捕获上述所有四个 URL,但不会将任何 / 传递给控制器​​?

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?

推荐答案

对于可选的尾部斜杠,您需要 在配置块中将严格模式设置为 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);
}]);

对于可选参数,这里有很长的讨论.最后,他们建议使用 squash:

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);
  }]
}

squash 有很好的 documentation,如果你设置为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-router 使用可选参数捕获此 URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆