AngularJS – Step 9: Routing

AngularJS Routing allows developers to create Single Page Applications (SPAs) by allowing the user to navigate between pages without a full-page reload. It uses the ngRoute module to achieve this functionality.

Now, let’s look at an example of how to implement routing in AngularJS.

First, we need to include the ngRoute module in our application by adding it as a dependency:

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

Next, we define our routes using the $routeProvider service:

app.config(function($routeProvider) {
    .when('/home', {
      templateUrl: 'partials/home.html',
      controller: 'HomeController'
    .when('/about', {
      templateUrl: 'partials/about.html',
      controller: 'AboutController'
    .when('/contact', {
      templateUrl: 'partials/contact.html',
      controller: 'ContactController'
      redirectTo: '/home'

In the above example, we have defined three routes for the pages – home, about, and contact. The otherwise method specifies the default route when none of the specified routes are matched.

We can then create controllers for each of these routes:

app.controller('HomeController', function($scope) {
  // Controller logic for home page

app.controller('AboutController', function($scope) {
  // Controller logic for about page

app.controller('ContactController', function($scope) {
  // Controller logic for contact page

Finally, we can add links to these routes in our HTML file:

<a href="#/home">Home</a>
<a href="#/about">About</a>
<a href="#/contact">Contact</a>

AngularJS will now automatically load the corresponding HTML and controller when the user navigates to these links.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.