【问题标题】:How to use AngularJS UI-router capture this URL with an optional parameter?如何使用 AngularJS UI-router 通过可选参数捕获此 URL?
【发布时间】:2016-01-03 10:19:22
【问题描述】:

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

  • 第一个参数是强制整数 (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 这正确捕获:

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

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

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

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

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

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

【问题讨论】:

    标签: angularjs regex angular-ui-router angularjs-routing


    【解决方案1】:

    对于可选的斜杠,您需要在配置块中set strict mode to false

    angular.module('yourModule').config(['$urlMatcherFactoryProvider', function($urlMatcherFactoryProvider) {
      $urlMatcherFactoryProvider.strictMode(false);
    }]);
    

    对于可选参数,here 进行了长时间的讨论。最后,他们建议使用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中的参数。

    【讨论】:

    • 谢谢!!我在哪里插入$urlMatcherFactoryProvider 的行?当我在 $stateProvider 行之前插入它时,我得到:Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to: ReferenceError: $urlMatcherFactoryProvider is not defined
    • 你需要先将它注入到你的配置函数中
    • @SaqibAli 顺便说一句,如果您对浏览器的代码进行 uglify/minify,您应该使用数组表示法来表示依赖项,请参阅我的 controller: 编辑。
    • $urlMatcherFactoryProvider 行似乎没有效果。我把它放在我的应用程序上,就像你指示的那样。 slug 和 id 正在被捕获......但只有在有斜杠的情况下(在任何一种情况下)
    • 您是否确保通过在其旁边放置一个 console.log 语句来执行该行?
    猜你喜欢
    • 2016-01-18
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 2014-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多