AngularJS Basics Part 3: Routing

In our last installment, we built a very simple Angular application from the ground up. In this post, I’ll focus in on AngularJS routing.

Routing is the process of connecting URL paths in your application to the view(s) and controller(s) that make that endpoint come alive. The views (typically HTML) and controllers (Angular-enhanced javascript are preloaded when the user first hits the web site, and for each URL in your application, the routing process dynamically combines the specific views and controllers you specify. It’s how Angular constructs a page, in contrast to the older style of web-database application servers like PHP, ASP.NET or Coldfusion, where the back-end server calculates would what the page should look like based on the URL and send back a pre-digested chunk of HTML (perhaps with relatively minor javascript thrown in for enhanced interactivity).

From a programming perspective, there are many possible ways to structure web applications in general, and more specifically many potential ways to structure an Angular application. In practice, most of the time most developers will pick a basic, tried-and-true application structure. Part of the “basics” for a small-to-medium size Angular app will include a straightforward routing mechanism like ngRoute, a module provided by the AngularJS team. There are other popular routing modules like the open source ui-router, which is a more powerful router generally used in larger applications with more complex routing needs (most notably nested views and a more powerful state-based routing approach).

Let’s look at the code below in some detail. The various sections of interest are separated by javascript comments. In our sample app we used ngRoute to create a default route we called “home”; this route was based off the “/” path which represents the root URL of our application (by “root” URL we just mean there is nothing in the URL after the domain name besides a slash). For that route, we specify the URL of the template (view) file as “homeView.html” and the associated controller as “myAppController”. Notice that the controller, in contrast to the template, is not defined by its URL but rather by name. In this case, the name is defined in the bottom block which defines myAppController.

// start angular module (app) definition
angular.module('myApp',['ngRoute'])
// end angular module (app) definition

// start config block with routing definition
 .config(function($routeProvider) {
   $routeProvider
   .when('/', {
    templateUrl: 'homeView.html',
    controller: 'myAppController'
    });
 })
// end config block with routing definition

// start definition of controller "myAppController"
 .controller('myAppController', function($scope) {
  $scope.user = {};
  $scope.user.firstName = 'Joe';
 });
// end definition of controller "myAppController"

To add more routes, we would chain more when calls to our $routeProvider configuration. The last route (“/about”) also demonstrates how we can also specify templates and controllers directly inline, on a route by route basis, using the template property to pass in a string instead and by providing a controller function directly instead of referring to an external controller by its name string.

At the end, we chain the otherwise call to provide a default route when no other route matches. In this case, we tell ngRoute to redirect to the “/” root URL as our fallback.

// end angular module (app) definition
...
// start config block with routing definition
 .config(function($routeProvider) {
   $routeProvider
   .when('/', {
      templateUrl: 'homeView.html',
      controller: 'myAppController'
    })
   .when('/userList', {
      templateUrl: 'userList.html',
      controller: 'myAppListController'
    })
   .when('/about', {
      template: '<div>Thanks for visiting {{message}}</div>',
      controller: function($scope){
        $scope.message = 'our beautiful web site.';
      }
    })
    .otherwise({
       redirectTo: '/'
    });

 })
// end config block with routing definition

While this blog gives you a starting point for exploring Angular’s ngRoute system, there is a lot more functionality possible. For example, templates can also be furnished by using a function that returns the template string; routes can be conditionally accessed based on whether or not a function permits access (useful for security measures such as a forced login system); and you can pass parameters in via url to create REST-ful interfaces. And lots more! To learn more, spend some time looking at the ngRoute docs on the official AngularJS site. If you’d like to explore more advanced routing possibilities and are at least somewhat familiar with the computer science concept of state machines, take a look at ui-router, the most popular 3rd party routing module that developers often substitute for ngRoute.

Leave a Reply

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