How to add guid regex in angular ui-router state

后端 未结 3 1496
庸人自扰
庸人自扰 2021-01-03 15:49

I have this route



        
相关标签:
3条回答
  • 2021-01-03 16:15

    You can define your own type of parameter.

    var GUID_REGEXP = /^[a-f\d]{8}-([a-f\d]{4}-){3}[a-f\d]{12}$/i;
    $urlMatcherFactoryProvider.type('guid', {
      encode: angular.identity,
      decode: angular.identity,
      is: function(item) {
         return GUID_REGEXP.test(item);
      }
    });
    

    Here is a showcase on plunker with this solution

    Then specify this type in url route expression:

    .state('mystate', {
      url: '/{id?guid}',
      templateUrl: '/views/partial.html'
    });
    

    You can read more on that page in docs

    0 讨论(0)
  • 2021-01-03 16:23

    After much trial and error, I came up with:

    $urlMatcherFactoryProvider.type('guid', {
        encode: angular.identity,
        decode: angular.identity,
        equals: function(a, b) { return a.toUpperCase() === b.toUpperCase(); },
        is: function(val) {
            // Local to avoid any lastIndex issues
            var GUID_REGEXP = /^[a-f\d]{8}-(?:[a-f\d]{4}-){3}[a-f\d]{12}$/i;
            return GUID_REGEXP.test(val);
        },
        // No anchors or flags with pattern
        pattern: /[a-fA-F\d]{8}-(?:[a-fA-F\d]{4}-){3}[a-fA-F\d]{12}/
    });
    

    This is based on @just-boris's answer. One key difference is pattern. Without this it appears that invalid GUIDs will not trigger $urlRouterProvider.otherwise().

    0 讨论(0)
  • 2021-01-03 16:30

    There is a working plunker

    We can just provide regexp in the url definition:

    url: "/{id:(?:[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12})}",
    

    Read more about our options for url defintion:

    http://angular-ui.github.io/ui-router/site/#/api/ui.router.util.type:UrlMatcher

    small snippet:

    '{' name ':' regexp|type '}' - curly placeholder with regexp or type name. Should the regexp itself contain curly braces, they must be in matched pairs or escaped with a backslash.

    0 讨论(0)
提交回复
热议问题