In AngularJS, the $routeProvider
service is part of the ngRoute module and is used for configuring routing in a Single Page Application (SPA). It allows navigation between different views based on the URL without reloading the page.
1. Installing ngRoute
Module
Before using $routeProvider
, you need to include ngRoute in your project.
Step 1: Include angular-route.js
Add the AngularJS routing script in your HTML file:
<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.js"></script>
Step 2: Inject ngRoute
in Your App
Define your AngularJS app and inject the ngRoute
module:
var app = angular.module("myApp", ["ngRoute"]);
2. Configuring Routes with $routeProvider
Use $routeProvider
inside .config()
to define your application routes.
Example: Setting Up Routes
app.config(function($routeProvider) {
$routeProvider
.when("/", {
templateUrl: "home.html",
controller: "HomeController"
})
.when("/about", {
templateUrl: "about.html",
controller: "AboutController"
})
.when("/contact", {
templateUrl: "contact.html",
controller: "ContactController"
})
.otherwise({
redirectTo: "/"
});
});
Explanation
.when(path, config)
: Defines a route for a specific URL path.templateUrl
: Specifies the HTML file to be loaded.controller
: Defines which controller should be used..otherwise({ redirectTo: "/" })
: Redirects to a default route if the URL doesn’t match any defined routes.
3. Creating Views
Each route needs a corresponding HTML file to be displayed.
Home Page (home.html
)
<h2>Welcome to Home Page</h2>
<p>This is the main page of our AngularJS app.</p>
About Page (about.html
)
<h2>About Us</h2>
<p>Learn more about our company.</p>
Contact Page (contact.html
)
<h2>Contact Us</h2>
<p>Feel free to reach out to us anytime.</p>
4. Creating Controllers
Each route can have its own controller to manage data and logic.
app.controller("HomeController", function($scope) {
$scope.message = "Welcome to the Home Page!";
});
app.controller("AboutController", function($scope) {
$scope.message = "Learn more about us on this page.";
});
app.controller("ContactController", function($scope) {
$scope.message = "Contact us for more information.";
});
5. Using ng-view
Directive
To load the views dynamically, place the ng-view
directive inside index.html
.
index.html
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<title>AngularJS Routing Example</title>
<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.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>
Explanation
<a href="#!/about">About</a>
: Defines a route link (#!
is required for AngularJS routing).<div ng-view></div>
: Placeholder where the views (home.html
,about.html
, etc.) will be loaded dynamically.
6. Handling Route Parameters
You can pass dynamic parameters in routes using :paramName
.
Example: Route with Parameters
app.config(function($routeProvider) {
$routeProvider
.when("/user/:id", {
templateUrl: "user.html",
controller: "UserController"
})
.otherwise({
redirectTo: "/"
});
});
User Controller
app.controller("UserController", function($scope, $routeParams) {
$scope.userId = $routeParams.id;
});
User Page (user.html
)
<h2>User Profile</h2>
<p>User ID: {{ userId }}</p>
Accessing Route
Visiting http://localhost/#/user/123
will display:
User ID: 123
7. Redirecting & Catching Invalid Routes
You can redirect unknown routes using .otherwise()
.
$routeProvider.otherwise({
redirectTo: "/"
});
To show a custom error page, use:
.when("/404", {
templateUrl: "404.html"
})
.otherwise({
redirectTo: "/404"
});
8. Route Resolvers (Fetching Data Before Navigation)
Sometimes, you need to fetch data before a route is loaded.
Example: Using resolve
in Routes
app.config(function($routeProvider) {
$routeProvider
.when("/profile", {
templateUrl: "profile.html",
controller: "ProfileController",
resolve: {
userData: function($http) {
return $http.get("https://jsonplaceholder.typicode.com/users/1")
.then(response => response.data);
}
}
});
});
Profile Controller
app.controller("ProfileController", function($scope, userData) {
$scope.user = userData;
});
Profile Page (profile.html
)
<h2>User Profile</h2>
<p>Name: {{ user.name }}</p>
<p>Email: {{ user.email }}</p>
The page will only load after the API call is completed.