AngularJS Routing

In a traditional website, clicking a link takes you to a completely new HTML page, causing the browser to refresh. Routing in AngularJS changes this dynamic by allowing you to navigate between different "views" within a single page. This creates a Single-Page Application (SPA) experience where content updates instantly without a full page reload. By using the ngRoute module, you can map specific URLs to specialized templates and controllers, making your app feel fast and responsive.

Developer Tip: Routing is the backbone of the "Single Page Application" (SPA) architecture. It allows you to maintain the state of your application while still giving users bookmarkable URLs.

Key Concepts of AngularJS Routing

  1. $routeProvider: This is the engine room where you configure your routes. It maps a URL path (like /dashboard) to a specific HTML file and a JavaScript controller.
  2. ng-view: Think of this as a dynamic container. It is a directive that tells AngularJS where to "inject" the HTML template for the current route.
  3. $location: A service that parses the browser URL and allows you to interact with it (reading or changing the path) via JavaScript.
  4. $route: This service manages the relationship between the current URL and the configuration you defined in the $routeProvider.
Best Practice: Always use ng-view as a structural element in your main layout file (usually index.html) to keep your global navigation (header/footer) consistent across all views.

 

How to Set Up AngularJS Routing

Step 1: Include ngRoute Module

Unlike the core AngularJS logic, routing is packaged in a separate file. You must include the angular-route.js script after the main AngularJS script to use these features.

Example:

<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>
Watch Out: If you forget to include the angular-route.min.js file, you will likely see an error stating that $routeProvider is undefined when you try to configure your module.

Step 2: Define Routes Using $routeProvider

To make the routing work, you need to "inject" the ngRoute module into your main application module. Then, you use a .config() block to set up your URL mapping.

Example:

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

app.config(function($routeProvider) {
  $routeProvider
    .when('/home', {
      templateUrl: 'home.html',
      controller: 'homeCtrl'
    })
    .when('/about', {
      templateUrl: 'about.html',
      controller: 'aboutCtrl'
    })
    .otherwise({
      redirectTo: '/home'
    });
});
  • when('/route', { ... }): This defines the "trigger" (the URL) and the "action" (which template to load and which controller handles the logic).
  • otherwise({ ... }): This acts as a catch-all safety net. If a user types a URL that doesn't exist, it redirects them to a safe default, like the home page.
Common Mistake: Beginners often forget to include the module dependency ['ngRoute'] in the angular.module declaration. Without this, the $routeProvider service won't be available in your config block.

Step 3: Add ng-view to the HTML Template

Your index.html serves as the shell for your app. The ng-view directive tells AngularJS exactly where to swap out content when the user navigates.

Example:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
  <title>AngularJS Routing</title>
</head>
<body>
  <nav>
    <!-- Use the # character before routes in AngularJS 1.x -->
    <a href="#!/home">Home</a> | 
    <a href="#!/about">About</a>
  </nav>
  
  <!-- The content from home.html or about.html will appear here -->
  <div ng-view></div>
  
  <script src="app.js"></script>
</body>
</html>
  • ng-view: Only one ng-view can exist in an application when using the standard ngRoute.
Developer Tip: Depending on your AngularJS version and configuration, you might need to use #!/ (the "hash-bang") in your links instead of just #/ to comply with modern browser routing standards.

 

Controllers for Each Route

By assigning a controller to a route, you ensure that the logic for a specific view is only loaded and executed when the user is actually looking at that view. This keeps your application organized and memory-efficient.

Example of homeCtrl and aboutCtrl:

app.controller('homeCtrl', function($scope) {
  $scope.message = "Welcome to the Home Page!";
  $scope.timestamp = new Date().toLocaleTimeString();
});

app.controller('aboutCtrl', function($scope) {
  $scope.message = "This is the About Page!";
  $scope.companyInfo = "We specialize in SPA development.";
});
Best Practice: Keep your controllers focused. A controller should only handle the logic for its specific view. If you need to share data between controllers, use an AngularJS Service or Factory.

 

Route Parameters

Real-world applications often need to load specific data based on an ID, such as a user profile or a product details page. This is where route parameters come in.

Example of Route with Parameters:

$routeProvider.when('/user/:userId', {
  templateUrl: 'user.html',
  controller: 'userCtrl'
});
  • :userId: The colon identifies this part of the URL as a variable. If the URL is /user/42, the userId will be 42.

 

Accessing Parameters in Controller:

To use the data passed in the URL, you must inject the $routeParams service into your controller.

app.controller('userCtrl', function($scope, $routeParams) {
  // If the URL is /user/101, then $routeParams.userId is '101'
  $scope.userId = $routeParams.userId;
  
  // Real-world example: Fetching user data from an API
  // UserService.getById($scope.userId).then(...)
});
Watch Out: Route parameters are always treated as strings. If you need to perform mathematical operations with a parameter (like userId + 1), make sure to convert it to a number using parseInt() first.

 

Nested Routes

While the standard ngRoute module is great for flat routing structures, you can simulate nested views by defining sub-paths. This allows you to create hierarchical navigation structures.

Example of Nested Path Patterns:

$routeProvider
  .when('/settings', {
    templateUrl: 'settings.html',
    controller: 'settingsCtrl'
  })
  .when('/settings/profile', {
    templateUrl: 'profile.html',
    controller: 'profileCtrl'
  })
  .when('/settings/password', {
    templateUrl: 'password.html',
    controller: 'passwordCtrl'
  });

In this structure, you can provide a seamless drill-down experience for the user. Note that for true nested ng-view components (a view inside a view), many professional developers opt for the ui-router library, though standard ngRoute works well for most simple-to-medium projects.

 

Using $location Service

Sometimes you need to change the page automatically without the user clicking a link—for example, redirecting a user to the login page if they aren't authenticated, or moving to a "Success" page after a form submission.

Example:

app.controller('loginCtrl', function($scope, $location) {
  $scope.login = function() {
    // Logic to verify credentials...
    var isAuthenticated = true; 
    
    if (isAuthenticated) {
      // Programmatically move the user to the dashboard
      $location.path('/dashboard');
    }
  };
});
  • $location.path('/path'): Updates the URL and triggers the router to load the corresponding view and controller.

 

Summary

AngularJS routing is a powerful tool that transforms your application from a collection of static files into a fluid, dynamic experience. By leveraging $routeProvider, you can define a clear navigation map, use ng-view to display content, and utilize $routeParams to handle dynamic data. Whether you are building a simple portfolio or a complex dashboard, mastering routing is essential for creating modern, professional-grade SPAs.