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??
At the core of the Angular router lies a powerful URL matching engine, which transforms URLs and converts them into router states. Understanding how this engine works is important for implementing advanced use cases.
The Angular Router supports a powerful matching strategy that you can use to help users navigate your application. This matching strategy supports static routes, variable routes with parameters, wildcard routes, and so on. You can also build your own custom pattern matching for situations in which the URLs are more complicated.
What is Angular UI-Router? The UI-Router is a routing framework for AngularJS built by the AngularUI team. It provides a different approach than ngRoute in that it changes your application views based on the state of the application and not just the route URL.
The angularJS service $routeProvider with ng-Route becomes $stateProvider when using UI-Router. $urlRouterProvider is used for two main reasons. To establish default route when URL does not meet with any route or does not have specific routes.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With