Cotten
Cotten

Reputation: 9077

Redirect angular route with trailing slash

Requirements:

/month      Redirect to /month/1   (january is the default month)
/month/     Redirect to /month/1
/month/4    No redirect, show april

My best attempt:

$routeProvider
  .when('/month/:monthNo', {
    templateUrl: 'views/month.html',
    controller: 'MonthCtrl'
  })

This works:

  .when('/month', {
    redirectTo: '/month/1'  // default redirect to january
  })

This doesn't (notice trialing slash: /month/):

  .when('/month/', {
    redirectTo: '/month/1' 
  })

The /month/ matches .when('/month/:monthNo'... so is something like this possible:

  .when('/month/:monthNo', {
    runThisCodeFirst: function() { if(!monthNo) redirectTo: '/month/1'}
    templateUrl: 'views/month.html',
    controller: 'MonthCtrl'
  })

Or are there any other solutions to this problem?

Upvotes: 1

Views: 2498

Answers (1)

Juliane Holzt
Juliane Holzt

Reputation: 2145

Could it be that you just make the .when calls in the wrong order? They are chained, so the first matching .when will end the processing. It works if I do it like this:

.when('/month', {
  redirectTo: '/month/1'
})
.when('/month/:monthNo', {
  template: 'This!'
})

However if I do it like this, I see the problem you are describing:

.when('/month/:monthNo', {
  template: 'This!'
})
.when('/month', {
  redirectTo: '/month/1'
})

So apparently '/month' also matches '/month/'. But so does '/month/:monthNo', therefore you want to have the redirecting rule first.

Upvotes: 2

Related Questions