如何使用 AngularJS UI

编程入门 行业动态 更新时间:2024-10-07 16:17:52
本文介绍了如何使用 AngularJS UI-router 使用可选参数捕获此 URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在使用 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-21 17:05:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1007912.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   AngularJS   UI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!