- Angular JS Tutorial
- AngularJS Home
- AngularJS Introduction
- AngularJS Expressions
- AngularJS Directives
- AngularJS Modules
- AngularJS Controllers
- AngularJS Scopes
- AngularJS Data Binding
- AngularJS Services
- AngularJS HTTP
- AngularJS Filters
- AngularJS Forms
- AngularJS Validation
- AngularJS DOM Manipulation
- AngularJS Select
- AngularJS Tables
- AngularJS Events
- AngularJS Routing
- AngularJS Includes
- AngularJS Animations
- AngularJS Dependency Injection
- AngularJS API
- AngularJS Deployment
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.
Key Concepts of AngularJS Routing
- $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. - 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.
- $location: A service that parses the browser URL and allows you to interact with it (reading or changing the path) via JavaScript.
- $route: This service manages the relationship between the current URL and the configuration you defined in the
$routeProvider.
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>
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.
['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-viewcan exist in an application when using the standardngRoute.
#!/ (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.";
});
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, theuserIdwill be42.
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(...)
});
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.