7

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.

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

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

2 Answers 2

18

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

The answer here would be: use the 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.

Example:

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

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

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks....I have list of names during config phase,so i just used join and $urlMatcherFactory and it worked.
Everything may be done in config phase without injecting $urlMatcherFactory. Forked plunk is here plnkr.co/edit/gDHagwOlJoftTakv7GwV?p=preview
Great job @sbedulin, thanks you spend some time to append that updated plunker. Great!
3

Previous answers are ok, but I most of the time need something simpler solution like this:

 url: '/something/{source:(?:' + ['John', 'Paul'].join('|') + ')}/:id',

without need for using $urlMatcherFactory

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.