Routes in AngularJS

Routes in AngularJS

September 29, 2015

Angular is a JavaScript framework that allows you to create single page web apps. Routes are a big part of the 'single page' aspect of things. They allow you to make Ajax calls to get different view files without doing a traditional page refresh. Thus, never leaving the first page you started at.

Getting set up

What we’ll do is start with most of the same HTML we had in Part 1: Getting Started with Angular.

<!DOCTYPE html>
<html lang="en" ng-app> 
<head>
<title>Brewitivity</title>
</head>
<body>
<!--AngularJS-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script>
<!--ngRoute module-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular-route.min.js"></script>
</body>
</html>

We’ve got the ng-app attribute in the HTML tag that turns on the power. And we’ve got our script for angular. We also have a new script for the ngRoute module. The ngRoute module isn’t part of the angular core script, however it was built and is maintained by the Angular team.

Let’s update one other thing and give the ng-app attribute a value of ‘brewitivity’ which is the name of our fictional app for brewing coffee and beer.

<!DOCTYPE html>
<html lang="en" ng-app="brewitivity"> 
<head>
<title>Brewitivity</title>
</head>
...

Creating the JS file

Now we want to create a JavaScript file that will store our routes. Let’s call this one app.js. Inside this file, before we do anything with routes, we’ll first need to define our app by creating a module called “brewitivity”. According to Joe Eames of the Adventures in Angular podcast, “Modules are the basic building blocks of Angular. Everything exists inside of a module.”

So let’s define a global variable called ‘brewitivity’ and set it equal to an Angular module with the name ‘brewitivity’.

//app.js
var brewitivity = angular.module('brewitivity', []);

‘brewitivity’ is as parameter of the module which is the same value we gave to the ng-app attribute in our HTML. They MUST match. Now we are going to pass in a second argument, which is just empty angle brackets.

Inside the angle brackets we’ll inject the ngRoute module.

//app.js
var brewitivity = angular.module('brewitivity', ['ngRoute']);

Bam! So, we’ve declared our app, and a basic building block, the ngRoute route module, has been injected in to our app.

Before we forget, let’s hook up this new script to our html file.

<body>
<!--AngularJS-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script>
<!--ngRoute module-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular-route.min.js"></script>
<!--app.js-->
<script src="app.js"></script>
</body>

Create the partial files that will be used to route to

Let’s also create a few more files that will be our pages we are linking to: home.html, beer.html, and coffee.html. For the sake of organization, all these files will go inside a folder called ‘partials‘. The entire folder structure should look like this.

//project root
  //index.html
  //app.js
  //partials
    //home.html
    //beer.html
    //coffee.html

Inside these 3 new partial files let’s add a single h1 tag with the following text inside it: “home”, “beer”, or “coffee” respectively. This way we can easily identify which file is which. There will be absolutely nothing in these files except for the h1 tag. That means no Doctype, body tag or anything else except the h1 tag.

Configuring the routes

Okay, so now back to the app.js file. All the routes need to go inside of the config function, which is used to register work that gets performed on module loading.

//app.js
var brewitivity = angular.module('brewitivity', ['ngRoute']);

brewitivity.config(function($routeProvider) {
  //routes go here
});

Our config function chains to the ‘brewitivity’ module and is getting passed a function which is getting the $routeProvider passed to it, which like its name implies, is used for configuring routes in Angular. Let’s take it a step further.

//app.js
var brewitivity = angular.module('brewitivity', ['ngRoute']);

brewitivity.config(function($routeProvider) {
  $routeProvider.
    when('/beer', {
      templateUrl: 'partials/beer.html'
    }).
    when('/coffee', {
      templateUrl: 'partials/coffee.html'
    }).
    when('/home', {
      templateUrl: 'partials/home.html'
    }).
    otherwise({
      redirectTo: '/home'
    });
});

So inside of the .config() block we’re using the $routeProvider to chain several .when() methods. Each .when() method takes two parameters: path (always a string) and route (always an object). The path is defining the url path and the object contains the partial file we’ll be using as our templateUrl. This is somewhat self explanatory, but I would describe it as, “when a certain path is entered in to the url bar, the following partial file will be used”. There are more properties we can add to the route object besides templateUrl but none of them are needed for our basic example.

We also have an .otherwise() method that according to the Angular docs: “Sets route definition that will be used on route change when no other route definition is matched.” This is basically the default. In our case we’ll use our home page, but it also very well could be your 404 page.

ngView and the navigation

Now let’s make life easier for us by creating a navigation in our index.html file we can use to access these different pages easily.

<h1>Brewitivity</h1>
<nav>
	<a href="#/home">Home</a>
	<a href="#/beer">Beer</a>
	<a href="#/coffee">Coffee</a>
	<a href="#/tea">Tea</a>
</nav>
<div ng-view></div>

There are four links: Home, Beer, Coffee, and Tea. Tea will be caught by our .otherwise catchall and route to the home page. Each href attribute isn’t pointing to a file, but instead pointing to one of our routes. You’ll need the hash in front of it in order to accomplish linking within a page. Browsers allow you to use a hash to specify additional information specifically for this purpose. The hash will show up in the url bar. However, there is a way to remove the hash but its a little outside the scope of this article.

We also have this div:

<div ng-view></div>

The ngView attribute is where all of our partials will be stuffed when the routes are called. Here’s what the entire html file will look like at this point:

<!DOCTYPE html>
<html lang="en" ng-app="brewitivity"> 
<head>
<title>Brewitivity</title>
</head>
<body>
<h1>Brewitivity</h1>
<nav>
	<a href="#/home">Home</a>
	<a href="#/beer">Beer</a>
	<a href="#/coffee">Coffee</a>
	<a href="#/tea">Tea</a>
</nav>
<div ng-view>
<!--partial files will be ajaxed in here-->
</div>
<!--AngularJS-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular.min.js"></script>
<!--ngRoute module-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.5/angular-route.min.js"></script>
<!--app.js-->
<script src="app.js"></script>
</body>
</html>

And at this point the routes should be fully functional. I created a video below that sums up what is mentioned in this article and shows you how it will look and behave in the browser.

Video recap


Conclusion

So that about explains it for routing using the ngRoute module in Angular. In the not-yet created part 3 of my Angular fundamentals series, I’ll walk you through pulling in some data in to these views using a controller.

Mastering CSS: Book by Rich Finelli
Mastering CSS, the Book! Flexbox, Layout, Animations, Responsive, Retina, and more!
Mastering CSS, 2nd Edition, video course by Rich Finelli
Mastering CSS, Second Edition: 47 videos on how to make websites like a boss! Flexbox, Animations, Responsive, Retina, and more!
Back to top