Easy Tutorial
❮ Angularjs Controllers Ng Ng Options ❯

AngularJS Routing

In this section, we will introduce AngularJS routing.

AngularJS routing allows us to access different content through different URLs.

With AngularJS, we can implement multi-view single-page web applications (SPA).

Typically, our URLs are in the form http://tutorialpro.org/first/page, but in single-page web applications, AngularJS uses #! + marker, for example:

http://tutorialpro.org/#!/first
http://tutorialpro.org/#!/second
http://tutorialpro.org/#!/third

Note that versions prior to Angular 1.6 used # + marker for routing.

When we click any of the above links, the address requested from the server is the same (http://tutorialpro.org/). This is because the content after the #! is ignored by the browser when making server requests. Therefore, we need to implement the functionality of the content after the #! on the client side. AngularJS routing helps us distinguish different logical pages and bind different pages to their corresponding controllers using #! + marker.

In the above diagram, we can see that two URLs are created: /ShowOrders and /AddNewOrder. Each URL has a corresponding view and controller.

Next, let's look at a simple example:

AngularJS Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>AngularJS Routing Example - tutorialpro.org</title>
<script src="https://cdn.bootcss.com/angular.js/1.7.0/angular.min.js"></script>
<script src="https://cdn.bootcss.com/angular.js/1.7.0/angular-route.min.js"></script>
</head>
<body ng-app='routingDemoApp'>

    <h2>AngularJS Routing Application</h2>
    <ul>
        <li><a href="#!/">Home</a></li>
        <li><a href="#!/computers">Computers</a></li>
        <li><a href="#!/printers">Printers</a></li>
        <li><a href="#!/blabla">Others</a></li>
    </ul>

    <div ng-view></div>
    <script>
        angular.module('routingDemoApp',['ngRoute'])
        .config(['$routeProvider', function($routeProvider){
            $routeProvider
            .when('/',{template:'This is the home page'})
            .when('/computers',{template:'This is the computers category page'})
            .when('/printers',{template:'This is the printers page'})
            .otherwise({redirectTo:'/'});
        }]);
    </script>
</body>
</html>

Example Explanation:

  1. Load the routing JS file: angular-route.js.

  2. Include the ngRoute module as a dependency of the main application module.

    angular.module('routingDemoApp',['ngRoute'])
    
  3. Use the ngView directive.

    <div ng-view></div>
    

The HTML content inside this div will change based on the route.

  1. Configure $routeProvider, which is used to define routing rules.
    module.config(['$routeProvider', function($routeProvider){
        $routeProvider
            .when('/',{template:'This is the home page'})
            .when('/computers',{template:'This is the computers category page'})
            .when('/printers',{template:'This is the printers page'})
            .otherwise({redirectTo:'/'});
    }]);
    

The config function of the AngularJS module is used to configure routing rules. By using the config API, we request to inject $routeProvider into our configuration function and use $routeProvider.when API to define our routing rules.

$routeProvider provides the when(path, object) & otherwise(object) functions to define all routes in order, with two parameters:


Route Configuration Object

AngularJS routing can also be implemented with different templates.

The syntax rules for the route configuration object are as follows:

$routeProvider.when(url, {
    template: string,
    templateUrl: string,
    controller: string, function, or array,
    controllerAs: string,
    redirectTo: string, function,
    resolve: object&lt;key, function>
});

Parameter Description:

template:

If we only need to insert simple HTML content into ng-view, we use this parameter:

.when('/computers',{template:'This is the computers category page'})

templateUrl:

If we only need to insert an HTML template file into ng-view, we use this parameter:

$routeProvider.when('/computers', {
    templateUrl: 'views/computers.html',
});

The above code will fetch the content of views/computers.html from the server and insert it into ng-view.

controller:

Function, string, or array type, the controller function to be executed on the current template, creating a new scope.

controllerAs:

String type, an alias for the controller.

redirectTo:

The redirect address.

resolve:

Specifies other modules that the current controller depends on.

Example

AngularJS Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>AngularJS Routing Example - tutorialpro.org</title>
<script src="https://cdn.bootcss.com/angular.js/1.7.0/angular.min.js"></script>
<script src="https://cdn.bootcss.com/angular.js/1.7.0/angular-route.min.js"></script>
<script type="text/javascript">
angular.module('ngRouteExample', ['ngRoute'])
.controller('HomeController', function ($scope, $route) { $scope.$route = $route;})
.controller('AboutController', function ($scope, $route) { $scope.$route = $route;})
.config(function ($routeProvider) {
    $routeProvider.
    when('/home', {
        templateUrl: 'embedded.home.html',
        controller: 'HomeController'
    }).
    when('/about', {
        templateUrl: 'embedded.about.html',
        controller: 'AboutController'
    }).
    otherwise({
        redirectTo: '/home'
    });
});
</script>


</head>

<body ng-app="ngRouteExample" class="ng-scope">
  <script type="text/ng-template" id="embedded.home.html">
      <h1> Home </h1>
  </script>

  <script type="text/ng-template" id="embedded.about.html">
      <h1> About </h1>
  </script>

  <div> 
    <div id="navigation">  
      <a href="#!/home">Home</a>
      <a href="#!/about">About</a>
    </div>

    <div ng-view="">
    </div>
  </div>
</body>
</html>
❮ Angularjs Controllers Ng Ng Options ❯