AngularJS Routing

One of the most important design patterns in web-based MVC systems like AngularJS is page routing. What is “page routing” in a nutshell?

Let’s take a look… one of the interesting capabilities of web-based MVC systems is the ability to swap in portions of a page without making a full page-load request, as happens with traditional html coding. Instead, some kind of small call is made to the server for a snippet of code that is swapped in somewhere in the view (the view in this case being the browser screen or some part of it).

Angular accomplishes this using the $routeProvider service. We wire this up by executing the following steps in this somewhat simple example that we’ll build on in future tutorials.

1. set up your application to use a specific module, with a name of your choice. This is done using the ng-app directive. Let choose the name “myApp” for our module — you could stick this snippet in your main index.html file:

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

The ng-view directive tells Angular exactly where the html snippet will be displayed.

2. Next we define the module using the angular.module construct as follows… make sure this code is referenced as a javascript file.

angular.module('myApp', [])
    .config(function ($routeProvider) {
        .when('/', {template: '<div>This is the default div</div>'})
        .when('/todolist', {templateURL: '/partials/todolist.html'})

You can either insert template code directly as using the template property as with the first .when chain for the $routeProvider, or you can reference an html file using the templateURL property, as we do in the second example that links to the /partials/todolist.html file.

3. Finally let’s create some links. Let’s use the ng-href directive to let Angular know to replace these links with Angular-friendly hashtagged URLs. Angular uses hashtags to enable in-page switching of views. Insert this code in your index.html page right after your ng-view div tag.

<a ng-href src="/">This is our main page</a>
<a hg-href src="/todolist">This is our todolist page link</a>

…And that’s it for this simple example. Refresh your index.html page and you should now have a very basic working Angular router. We’ll build on this example in future installments.

6 thoughts on “AngularJS Routing

  1. JoSeTe

    Thank you very much for this blog iniciative, highly recommended for introduction into this MVC Javascript framework.

    1. Ashique

      Hi i tried this
      <a hg-href src="/todolist">This is our todolist page link</a>

      it seems there is a typo error, it should be as follows
      <a ng-href="/todolist">This is our todolist page link</a>


Leave a Reply

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