Reputation: 7707
On AngularJS 1.1.5, I've got two mapped routes in the form:
/category/:name/:article
/category/:name
I'd like to only have the latest, and route the param :article to a action. This action is actually expanding an element in a list, so I don't need to reload the controller, etc or let's imagine in other circumstance could be for example running an animation. For example, let's say I had a slideshow and I wanted to show the slide number 5 - this sort of thing! No need to reload everything!
The routes (I'm using the slider example as it's less confusing):
.config(function(...))
$routePRovider
.when('/slider/:category', {
templateUrl: 'slider.html',
controller: 'sliderCtrl'
})
.when('/slider/:category/:number', {
templateUrl: 'slider.html',
controller: 'sliderCtrl'
});
Then on .run() or .controller(),
scope.$on("$locationChangeStart", function(event, next, current){
var path = $location.path();
if((path.match("\/slider\/(.+)\/(.+)"))){ ... }; /* I'd like the 2 param to be optional, I'm still trying to find the right or correct regex for this atm. I knnow that I'll have to keep just one routemap controller, the one without the :number param */
})
After some research I found a possible solution:
The pattern
"/foo/bar/das".match("\/foo\/([^\/]+)(\/[^\/]+)?")
returns the three params and only two if the last omitted, but I get the extra "/", as in ["foo", "bar", "/das"] and ["foo", "bar", undefined]. I'm fine having to deal with the extra "/" though!
This one is working nicely:
"/foo/bar".match("\/foo\/([^\/]+)(?:\/([^\/]+))?")
After some testing and finding the pattern, at the moment it looks like AngularJS 1.15 $routeProvider doesn't really support it? I've posted this, thinking that, by keeping only one routeMapper for /foo/:bar/:das where third param is optional could work as /foo/:bar and then using regex on locationChange().
Upvotes: 0
Views: 693
Reputation: 785126
To make both params optional you can use:
var m = path.match(/issue(?:\/([^/]*))?(?:\/([^/]*))?/i);
Upvotes: 0