A Bit of Routing Confusion

So, I was working on an angular app, and just when I thought I’d successfully implemented my new poll page, the wrong page kept loading on the page. Frustration ensued until I finally realize what was happening. It was loading the wrong page because I was telling it to load the wrong page. The culprit code is show below:


.config(function ($routeProvider) {
  $routeProvider
  .when('/polls/:id', {
    templateUrl: 'app/poll/show.html',
    controller: 'PollShowCtrl'
  })

  .when('/polls/new', {
    templateUrl: 'app/poll/new.html',
    controller: 'PollCreateCtrl'
  })

});

The way the router works is like this: It takes the path and then chugs along through the routes until it sees one that matches the pattern present in the path. When you use parameters in the route like :id that I have above, that acts sort of like a wild card. the route assumes that anything that comes after ‘/polls/’ must be :id. It has no way of knowing that when I send in ‘/polls/new’ that new is not the parameter :id. So it will never reach the ‘/polls/new’ route. To fix this all you have to do is switch the order of your routes like so:


.config(function ($routeProvider) {
  $routeProvider

  .when('/polls/new', {
    templateUrl: 'app/poll/new.html',
    controller: 'PollCreateCtrl'
  })
  .when('/polls/:id', {
    templateUrl: 'app/poll/show.html',
    controller: 'PollShowCtrl'
  })
});

Since the first route only matches if the path is exactly ‘/polls/new’ this will now work both for the case of trying to go to the new poll page and also to go to the route that takes the :id as the value immediately after ‘/polls/’. The moral of the story here is to always start with your most specific routes first and then move on to more general routes. This ensures that you don’t accidentally match a route that just happens to be too broad.

Leave a Reply

Your email address will not be published. Required fields are marked *