AngularJS Template Route Provider Tutorial Image

AngularJS Template Route Provider Tutorial

Table Of Contents

This tutorial covers how you can utilize AngularJS’s $routeProvider in order to create a multiple page application that features one master page. The official documentation for Routing and multiple views can be found here: https://docs.angularjs.org/tutorial/step_07

Our Project

The structure of our project for this tutorial is going to look a little something like this:

1
2
3
4
5
6
index.html
scripts.js
view/
-- home.html
-- contact.html
-- about.html

With our index.html being our master page in which we define all javascript dependencies and styling for things like the nav bar and footer etc. We would then typically put all of our page specific content in their own html files. This can be incredibly handy for times when you want to make a simple change to the header of your site that you want reflected across your whole site as it means you only have to make the change in one place.

Implementation

In this tutorial we’ll define some relatively simple routes that each have their own defined controllers and templates.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
var testApp = angular.module('testApp', ['ngRoute']);

testApp.config(function($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl : 'views/home.html',
            controller  : 'testController'
        })
        .when('/about', {
            templateUrl : 'views/about.html',
            controller  : 'AboutController'
        })
        .when('/contact', {
            templateUrl : 'views/contact.html',
            controller  : 'ContactController'
        });
});

testApp.controller('testController' , function ($scope) {
   $scope.home = "This is the homepage";
});

testApp.controller('AboutController', function($scope) {
    $scope.about = "You are awesome";
});

testApp.controller('ContactController', function($scope) {
    $scope.contact = "You can't contact me, go away.";
});

Our Index.html Page:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
<html ng-app="testApp">
<head>
    <title>AngularJS ng-if child scopes example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular-route.min.js"></script>
</head>
<body ng-controller="testController">
    
    <h2>Routing Tutorial</h2>
    
    <div ng-view></div>
    
    <script src="scripts.js"></script>
</body>
</html>

And finally our 3 pages, concatenated into one gist for brevity.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<!-- OUR ABOUT.HTML -->
{{about}}
<!-- END OF ABOUT.HTML -->

<!-- OUR CONTACT.HTML -->
{{contact}}
<!-- END OF CONTACT.HTML -->

<!-- OUR HOME.HTML -->
{{home}}
<!-- END OF HOME.HTML -->
Was This Post Helpful?
Submit a PR: Edit on Github