🧭 AngularJS Routing & Navigation
Estimated reading: 4 minutes 28 views

πŸ›£οΈ AngularJS Routing – Navigate Between Views Using ngRoute (2025 Guide)

🧲 Introduction – Why Learn AngularJS Routing?

Single Page Applications (SPAs) rely heavily on client-side routing to navigate between views without reloading the page. AngularJS supports this functionality through its ngRoute module, which allows you to map URLs to templates and controllersβ€”creating smooth, dynamic navigation within your app.

Routing is essential for:

  • Dividing your application into manageable views
  • Navigating between pages like Home, About, Contact
  • Loading content dynamically based on route

🎯 In this guide, you’ll learn:

  • How AngularJS routing works using ngRoute
  • How to set up route configurations
  • Create and link views dynamically
  • Use route parameters for dynamic content
  • Handle undefined routes (404 fallback)

βš™οΈ Prerequisites

  • AngularJS library
  • angular-route.js included via CDN or local file

CDN example:

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

πŸ“ Basic Folder Structure

/angularjs-routing-app
β”‚
β”œβ”€β”€ index.html
β”œβ”€β”€ app.js
β”œβ”€β”€ views/
β”‚   β”œβ”€β”€ home.html
β”‚   β”œβ”€β”€ about.html
β”‚   └── contact.html

βœ… Step 1: Configure Routes with $routeProvider

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: '/'
    });
});

βœ… Step 2: Define Controllers

app.controller('HomeCtrl', function($scope) {
  $scope.message = "Welcome to the Home Page";
});
app.controller('AboutCtrl', function($scope) {
  $scope.message = "Learn more About Us";
});
app.controller('ContactCtrl', function($scope) {
  $scope.message = "Contact us at support@example.com";
});

βœ… Step 3: Main Template (index.html)

<!DOCTYPE html>
<html ng-app="myApp">
<head>
  <title>AngularJS Routing</title>
  <script src="angular.min.js"></script>
  <script src="angular-route.min.js"></script>
  <script src="app.js"></script>
</head>
<body>

  <nav>
    <a href="#!/">Home</a> |
    <a href="#!/about">About</a> |
    <a href="#!/contact">Contact</a>
  </nav>

  <div ng-view></div>

</body>
</html>

πŸ“„ Sample View – home.html

<h2>Home</h2>
<p>{{ message }}</p>

🧾 The ng-view directive loads the content based on the current URL hash.


πŸ” Using Route Parameters

βœ… Define a Route with Parameter

.when('/user/:id', {
  templateUrl: 'views/user.html',
  controller: 'UserCtrl'
})

βœ… Access the Parameter in Controller

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

βœ… Example URL:

http://localhost/#/user/42

🧾 This will render user.html and set $scope.userId to 42.


🧠 Real-World Use Case – Blog Post Navigation

.when('/post/:postId', {
  templateUrl: 'views/post.html',
  controller: 'PostCtrl'
});
app.controller('PostCtrl', function($scope, $routeParams, PostService) {
  var id = $routeParams.postId;
  $scope.post = PostService.getPost(id);
});

🚫 Handling Unknown Routes (404)

.otherwise({
  template: '<h3>404 – Page Not Found</h3>'
});

βœ… Ensures that users are shown a friendly message when they hit an unknown route.


πŸ› οΈ Best Practices

βœ”οΈ Use ng-view as a placeholder for route content
βœ”οΈ Always configure otherwise() to handle invalid URLs
βœ”οΈ Modularize each route’s controller and template
βœ”οΈ Use services to fetch data in route controllers
βœ”οΈ Use hashbang (#!) URLs for older browser support


πŸ“Œ Summary – Recap & Next Steps

AngularJS routing helps you build true single-page applications where users can navigate through multiple views without full page reloads. It’s simple to set up, easy to manage, and crucial for modern app structure.

πŸ” Key Takeaways:

  • Use $routeProvider to define routes
  • Load templates dynamically with ng-view
  • Access parameters with $routeParams
  • Handle undefined routes with otherwise()

βš™οΈ Real-world Relevance:
Used in SPAs like CRMs, blog systems, eCommerce dashboards, portfolio sites, admin panels, and interactive web portals.


❓ FAQ – AngularJS Routing


❓ What is ngRoute used for in AngularJS?
βœ… It enables routing between different views without reloading the entire page.


❓ What does ng-view do?
βœ… It serves as a placeholder in the HTML to load the template associated with the current route.


❓ How do you pass dynamic values in routes?
βœ… Use colon syntax like /user/:id, and retrieve it using $routeParams.


❓ How can I show a 404 page for unknown routes?
βœ… Use .otherwise() in $routeProvider to define a fallback template or redirect.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ›£οΈ AngularJS Routing

Or Copy Link

CONTENTS
Scroll to Top