In AngularJS, redirecting routes ensures users are guided to the correct pages when they enter invalid URLs, access deprecated routes, or require authentication before viewing a page. The $routeProvider
module helps define redirect rules for a seamless user experience.
2. Using $routeProvider.redirectTo()
for Redirection
The $routeProvider.redirectTo()
method is used to redirect users from one route to another.
Example: Redirect /home
to /dashboard
var app = angular.module("myApp", ["ngRoute"]);
app.config(function($routeProvider) {
$routeProvider
.when("/dashboard", {
templateUrl: "dashboard.html",
controller: "DashboardController"
})
.when("/home", {
redirectTo: "/dashboard"
})
.otherwise({
redirectTo: "/404"
});
});
How It Works:
- When the user visits
http://example.com/#!/home
, they are redirected tohttp://example.com/#!/dashboard
. - If the user enters an invalid route, they are redirected to
404.html
.
3. Using $location.path()
for Dynamic Redirection
Sometimes, redirection needs to be handled dynamically inside controllers.
Example: Redirect to /login
if the user is not authenticated
app.controller("ProfileController", function($scope, $location, AuthService) {
if (!AuthService.isAuthenticated()) {
$location.path("/login");
}
});
How It Works:
- If the user is not authenticated, they are redirected to
/login
. - This prevents unauthorized users from accessing the profile page.
4. Redirecting with $location.replace()
By default, $location.path("/newPage")
adds a new entry in the browser’s history. To prevent users from going back, use $location.replace()
.
Example: Redirect without adding to history
app.controller("LoginController", function($scope, $location) {
$scope.login = function() {
// After login success
$location.path("/dashboard");
$location.replace(); // Prevents back button from returning to login page
};
});
Why Use $location.replace()
?
- The back button won’t take users back to the login page after authentication.
5. Redirecting Based on User Roles
For role-based redirection, use services to check permissions.
Example: Redirect Admins to Admin Dashboard
app.controller("DashboardController", function($scope, $location, AuthService) {
var userRole = AuthService.getUserRole();
if (userRole === "admin") {
$location.path("/admin-dashboard");
} else {
$location.path("/user-dashboard");
}
});
How It Works:
- If the user is an admin, they go to
/admin-dashboard
. - Regular users go to
/user-dashboard
.
6. Redirecting to a 404 Page
A good practice is to handle invalid routes with a 404 page.
Example: Redirect to 404.html
for Undefined Routes
$routeProvider.otherwise({
templateUrl: "404.html",
controller: "NotFoundController"
});
How It Works:
- If a user enters an unknown route like
http://example.com/#!/unknown
, they see a 404 error page.
7. Redirecting with URL Parameters
Sometimes, we need to pass URL parameters when redirecting.
Example: Redirect /profile/:userId
to /user/:userId
app.config(function($routeProvider) {
$routeProvider
.when("/profile/:userId", {
redirectTo: function(routeParams) {
return "/user/" + routeParams.userId;
}
})
.when("/user/:userId", {
templateUrl: "user.html",
controller: "UserController"
});
});
How It Works:
- A user visiting
/profile/123
is automatically redirected to/user/123
.
8. Redirecting After API Calls
If an API response requires redirection, do it inside $http.then()
.
Example: Redirect After a Successful Login
app.controller("LoginController", function($scope, $http, $location) {
$scope.login = function(user) {
$http.post("/api/login", user)
.then(function(response) {
if (response.data.success) {
$location.path("/dashboard");
} else {
$scope.errorMessage = "Invalid credentials!";
}
});
};
});
✅ How It Works:
- After a successful login, the user is redirected to
/dashboard