How to implement wildcard routes (*)

Loading

In AngularJS, wildcard routes are a useful feature that allows you to handle routes that do not exactly match any of your predefined routes. This is commonly used for scenarios like redirecting users to a default route, displaying a “404 – Not Found” page, or handling unknown routes dynamically.

This guide will explain how to implement wildcard routes in AngularJS and provide practical examples for different use cases.


1. Understanding Wildcard Routes in AngularJS

Wildcard routes are a feature of the $routeProvider configuration, where you can define a route that matches any URL pattern that doesn’t match a more specific route. The wildcard route typically uses an asterisk * and is usually placed at the end of the route configuration to catch all unmatched routes.

Wildcard routes are typically used for:

  • Redirecting users to a default or home page when they enter an unknown URL.
  • Displaying a “404 – Not Found” page for invalid routes.
  • Handling dynamic, catch-all routing behavior.

2. Setting Up Wildcard Routes

In AngularJS, wildcard routes are configured using $routeProvider. You define a route with the path * to catch all routes that do not match any of the previous defined routes.

Basic Wildcard Route Example

Here’s how you can implement a wildcard route that redirects users to the home page when they try to visit an unknown or invalid route:

app.config(function($routeProvider) {
// Define valid routes
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
})
.otherwise({
redirectTo: '/home' // Wildcard route that redirects to /home
});
});

In this configuration:

  • The otherwise method is used to define the wildcard route, which catches all unmatched routes and redirects them to the /home route.
  • If the user tries to visit an invalid URL (e.g., /unknown), they will be redirected to the /home route.

3. Handling 404 – Not Found Page with Wildcard Route

Another common use case for wildcard routes is to show a “404 – Not Found” page for any invalid routes.

404 Page Example

app.config(function($routeProvider) {
// Define valid routes
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
})
.otherwise({
templateUrl: '404.html', // Wildcard route that loads a 404 page
controller: 'NotFoundController'
});
});

In this example:

  • The otherwise method is used to load a 404.html template and a NotFoundController when the user navigates to an invalid or unknown route.
  • This helps create a user-friendly experience by showing a custom 404 page instead of a blank page or error.

404 Page Controller

app.controller('NotFoundController', function($scope) {
$scope.message = "Oops! The page you are looking for doesn't exist.";
});

Here, the NotFoundController displays a message indicating that the page the user tried to visit does not exist.


4. Redirecting to a Default Route with Wildcard

In some cases, you may want to redirect users to a default route based on certain conditions or after a delay. Wildcard routes can be useful for this purpose as well.

Redirecting to Default Route Example

app.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
})
.otherwise({
redirectTo: function() {
// Logic to determine the default route
return '/home'; // Always redirect to /home if route is invalid
}
});
});

In this configuration:

  • The redirectTo function is used in the wildcard route, and you can add logic to determine which route to redirect the user to dynamically.
  • For instance, you could redirect to a home page, login page, or any other page based on the user’s authentication status or other criteria.

5. Wildcard Routes with UI-Router

If you are using UI-Router instead of AngularJS’s built-in $routeProvider, you can also define wildcard routes with UI-Router.

UI-Router Wildcard Route Example

app.config(function($stateProvider, $urlRouterProvider) {
// Define states (routes)
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home.html',
controller: 'HomeController'
})
.state('about', {
url: '/about',
templateUrl: 'about.html',
controller: 'AboutController'
});

// Wildcard route with UI-Router
$urlRouterProvider.otherwise('/home'); // Redirect to home if the route is invalid
});

In this UI-Router example:

  • The $urlRouterProvider.otherwise() method is used to define the wildcard route, redirecting to the /home route if no match is found.
  • You can replace /home with any other route you wish to be the default fallback route.

6. Advanced Use Case: Dynamic Wildcard Routes

Sometimes you might want to handle dynamic wildcard routes based on conditions. For example, you can capture route parameters or redirect users based on certain conditions, such as user roles or authentication status.

Dynamic Wildcard Route Example

app.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeController'
})
.when('/about', {
templateUrl: 'about.html',
controller: 'AboutController'
})
.otherwise({
redirectTo: function($routeParams) {
// Check if a parameter exists and redirect based on the condition
if ($routeParams.role === 'admin') {
return '/admin';
} else {
return '/home'; // Default redirect to home if no matching route is found
}
}
});
});

In this example:

  • The wildcard route checks the route parameters, and based on the user role (admin in this case), redirects them to a specific route.

7. Best Practices for Using Wildcard Routes

  • Always Define a Default Route: Ensure that the wildcard route either redirects the user to a valid route or displays a useful page (such as a 404 page).
  • Avoid Overusing Wildcard Routes: Relying too much on wildcard routes can make your application behave unpredictably and hard to debug. Try to use explicit route definitions as much as possible.
  • Handle User Experience: Redirecting users to a home or login page when they try to access an invalid route is essential for providing a good user experience.
  • SEO Considerations: If SEO (Search Engine Optimization) is important for your application, make sure that the wildcard route does not interfere with the indexing of your pages. For SPAs, consider using AngularJS’s HTML5 mode to create clean URLs.

Leave a Reply

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