正则表达式 – 匹配URL与AngularJS ui-router中的数组列表

使用AngularJS ui-router,我需要将一个url与单词列表匹配:

但是,使用正则表达式我尝试使用一个或两个单词,它的工作原理

url: '/{source:(?:John|Paul)}/:id'

但我需要将我的网址与单词列表相匹配.

例:
var sourceList = [‘John’,’Paul’,’George’,’Ringo’];
url:’/ {source :(?:sourceList)} /:id’

有没有办法比较我的网址与匹配的数组列表?

不完全确定你究竟在搜索什么…因为它可能是动态网址匹配器或只是智能正则表达式.这是一个 plunker with working example.它实际上1)只从通过的名单列表构建正则表达式… 2)显示urlMatcher在行动

这里的答案是:使用UrlMatcher.

$urlMatcherFactory and UrlMatchers

Defines the Syntax for url patterns and parameter placeholders. This factory service is used behind the scenes by $urlRouterProvider to cache compiled UrlMatcher objects,instead of having to re-parse url patterns on every location change. Most users will not need to use $urlMatcherFactory directly,however it Could be useful to craft a UrlMatcher object and pass it as the url to the state config.

例:

var urlMatcher = $urlMatcherFactory.compile("/home/:id?param1");
$stateProvider.state('myState',{
    url: urlMatcher 
});

plunker中的例子:

var sourceList= ['John','Paul','George','Ringo']
  var names = sourceList.join('|');
  var urlMatcher = $urlMatcherFactory.compile("/{source:(?:" + names + ")}/:id");

  $stateProviderRef 
    .state('names',{ 
      url: urlMatcher,templateUrl: 'tpl.root.html',controller: 'MyCtrl'
    });

example显示一个更复杂的解决方案.如果我们在cofnig阶段确实有名单列表……简单连接应该有效.但如果稍后(.run())通过$http可以使用…这个解决方案可以提供帮助

相关文章

正则替换html代码中img标签的src值在开发富文本信息在移动端...
正则表达式
AWK是一种处理文本文件的语言,是一个强大的文件分析工具。它...
正则表达式是特殊的字符序列,利用事先定义好的特定字符以及...
Python界一名小学生,热心分享编程学习。
收集整理每周优质开发者内容,包括、、等方面。每周五定期发...