将url与AngularJS ui-router中的单词数组列表匹配数组、单词、列表、AngularJS

2023-09-06 08:25:28 作者:别让梦枯萎

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

Using AngularJS + ui-router, I need to match a url with list of words:

但是,我尝试使用一个或两个单词的正则表达式并且它起作用了

However, using a regex I have tried using one or 2 words and it worked

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

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

But i need to match my url with an list of words.

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

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

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

is there way to compare my url with matching list of array??

推荐答案

不完全确定您到底在搜索什么...因为它可能是动态 url 匹配器或只是智能正则表达式.这是一个 plunker 和工作示例.它实际上 1) 仅从传递的名称列表中构建正则表达式... 2) 显示 urlMatcher 的作用

Not fully sure what exactly you are searching for... because it could be a dynamic url matcher or just smart regex. Here is a plunker with working example. It in fact 1) only builds the regex from the passed list of names... 2) shows urlMatcher in action

这里的答案是:使用 UrlMatcher.

The answer here would be: use the UrlMatcher.

定义 url 模式和参数占位符的语法.$urlRouterProvider 在后台使用此工厂服务来缓存已编译的 UrlMatcher 对象,而不必在每次位置更改时重新解析 url 模式.大多数用户不需要直接使用 $urlMatcherFactory,但是制作一个 UrlMatcher 对象并将其作为 url 传递给状态配置可能很有用.

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 中的例子:

The example in 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'
    });

示例展示了一个更复杂的解决方案.如果我们在 cofnig 阶段确实有名称列表......简单的连接应该可以工作.但是,如果以后可以通过 $http 使用它(.run())......这个解决方案可能会有所帮助

The example is showing a bit more complex solution. If we do have the list of names during cofnig phase... the simple join should work. But if it will be availabel later (.run()) via $http ... this solution could help