Episode 16 of 25

Views and Routes

Learn how to create a single-page application with AngularJS routing.

Routing lets you create a single-page application (SPA) with multiple views without full page reloads.

Setting Up ngRoute

First, include the Angular Route module:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular-route.min.js"></script>

Configuring Routes

var app = angular.module('myApp', ['ngRoute']);

app.config(function($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: 'views/home.html',
            controller: 'HomeCtrl'
        })
        .when('/about', {
            templateUrl: 'views/about.html',
            controller: 'AboutCtrl'
        })
        .when('/contact', {
            templateUrl: 'views/contact.html',
            controller: 'ContactCtrl'
        })
        .otherwise({
            redirectTo: '/'
        });
});

The ng-view Directive

<body ng-app="myApp">
    <nav>
        <a href="#/">Home</a>
        <a href="#/about">About</a>
        <a href="#/contact">Contact</a>
    </nav>

    <!-- Views are loaded here -->
    <div ng-view></div>
</body>

View Templates

<!-- views/home.html -->
<h1>Home</h1>
<p>Welcome to our site!</p>

<!-- views/about.html -->
<h1>About</h1>
<p>Learn more about us.</p>

Route Parameters

$routeProvider.when('/user/:userId', {
    templateUrl: 'views/user.html',
    controller: 'UserCtrl'
});

app.controller('UserCtrl', function($scope, $routeParams) {
    $scope.userId = $routeParams.userId;
});