How to use AngularJS UI-router capture this URL with an optional parameter?

 ̄綄美尐妖づ 提交于 2020-01-07 02:55:30

问题


I'm using AngularJD ui-router to capture my URL and send two parameters from that URL to my controller. Here are my requirements:

  • The first parameter is a mandatory integer (id)
  • The second parameter is an optional string (slug)
  • The two parameters are separated by a /
  • I want it to ignore any single trailing /

Currently, I'm doing this:

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

For URL: mystate/1 This correctly captures:

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

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

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

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

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

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?


回答1:


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

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 has good documentation, if you set it to true, it omits the parameter from URL when it has the default value.



来源:https://stackoverflow.com/questions/34575444/how-to-use-angularjs-ui-router-capture-this-url-with-an-optional-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!