AngularJS Routing


The ngRoute module helps your application to become a Single Page Application (SPA).


What is Routing in AngularJS?


If you want to navigate to different pages in your application, but you also want the application to be a SPA (Single Page Application), with no page reloading, you can use the ngRoute module.

The ngRoute module routes your application to different pages without reloading the entire application.

Output :



What do I Need?

To make your applications ready for routing, you must include the AngularJS Route module:

To use Angular's routing capabilities, you first need to include the angular-route.js script:

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

Then you must add the ngRoute as a dependency in the application module:

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

Now your application has access to the route module, which provides the $routeProvider.

Use the $routeProvider to configure different routes in your application:

app.config(function($routeProvider) {
  $routeProvider
    .when("/", {
      templateUrl : "main.htm"
    })
    .when("/red", {
      templateUrl : "red.htm"
    })
    .when("/green", {
      templateUrl : "green.htm"
    })
    .when("/blue", {
      templateUrl : "blue.htm"
    });
});

Where Does it Go?

Your application needs a container to put the content provided by the routing.

This container is the ng-view directive.

Output :


$routeProvider

With the $routeProvider, you can define what page to display when a user clicks a link.

The $routeProvider is used with the config method of your AngularJS application.

Work registered inside the config method will be executed while the application is loading.

Output :


Controllers

With the $routeProvider you can also define a controller for each "view".

The "Python.html" and "Angular.html" are normal HTML files, which you can add AngularJS expressions as you would with any other HTML sections of your AngularJS application.

Template

In the previous examples we have used the templateUrl property in the $routeProvider.when method.
You can also use the template property, which allows you to write HTML directly in the property value, and not refer to a page.

Output :



The otherwise method

In the previous examples we have used the when method of the $routeProvider.
You can also use the otherwise method, which is the default route when none of the others get a match.:

Output :