AngularJS routeProvider

Let’s continue building out our PetStore from the earlier Angular intro post.

Let’s recall we had the following line in our app/index.html

<div ng-include="'views/main.html'" ng-controller="MainCtrl"></div>

We didn’t really go over ng-include when going over Angular intro. It’s a new directive that fetches and includes an external html fragment.

####What’s wrong here? Nothing .. It’s OK to use the ng-include directive to load the internal view on the main page, however if we want better control over what to display on that view based on some routes the user is interested in, we may have more flexibility. For example: on the PetStore we’d like to show a list of pets when the user wants to visit the home page (clicks on the “home” tab), or we’d like to display the “about us” information when the users wants to visit the about page (clicks on the “about” tab). We can do so by using Angular Routes.

####Angular Routes

Angular Logo

Angular provides ngRoute module for routing ($routeProvider) / deeplinking services ($route) and directives (ng-view). Instead of me describing these in detail and echoing the docs that are already out there, let’s get straight to using these in our PetStore.

The first step is installing the module. The following does the trick:

bower install --save angular-route#1.2.16

NOTE: the --save tells yeoman to save the dependency in the bower.json file and running grunt serve again after the change is saved, will allow grunt to push those changes in the app/index.html (meaning we’ll have all the js files inserted for us). For the version number locking, checkout the issue section at the end of this post

So first things first … lets replace the ng-include with the ng-view directive.

That means, we need to replace

<div ng-include="'views/main.html'" ng-controller="MainCtrl"></div>

with

<div ng-view=""></div>

All we need now is some way to control this view based on when a route is picked. $routeProvider to the rescue.

In our app/script/app.js we need to add the $routeProvider and the locations we’d like to support:

We need to add the about view views/about.html and a controller for it in the mix. Also note the otherwise condition that points back to home page. The complete change commit is available here. Hope this helps!

####Issues I ran into

There were some issues I ran into and thought may as well share them here:

  • I kept getting Unknown provider: $templateRequestProvider <- $templateRequest ... Remember bower install --save angular-route#1.2.16 .. locking it down to the version number was the solution.

  • grunt serve wasn’t working so I had to use grunt serve --force Following the advise here the change we’ll have to make is here

regards

======================================================================

Published: January 13 2015

See an error in this post? Please submit a PR on Github.