In AngularJS, it’s crucial to handle default routes and provide a 404 page (page not found) for any invalid or undefined URLs. This ensures that users are redirected to appropriate pages when they navigate to routes that are not explicitly defined.
In this guide, we will walk you through how to define default routes and handle 404 pages in your AngularJS application.
Step 1: Setting Up Your AngularJS Application
Let’s start by creating a basic AngularJS application. First, ensure you have AngularJS and UI Router set up in your project.
Here’s a simple HTML structure:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AngularJS Default Route and 404 Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.4.2/angular-ui-router.min.js"></script>
</head>
<body ng-app="myApp">
<div>
<a ui-sref="home">Home</a> |
<a ui-sref="about">About</a> |
<a ui-sref="contact">Contact</a>
</div>
<div ui-view></div>
<script src="app.js"></script>
</body>
</html>
Step 2: Configure Routes with UI Router
In your app.js file, use UI Router to define the states (routes). UI Router helps you map each state to a specific URL and view. Here, we’ll define routes for home
, about
, and contact
, as well as a fallback route for an invalid or undefined URL.
var app = angular.module('myApp', ['ui.router']);
app.config(function($stateProvider, $urlRouterProvider) {
// Default Route - Home
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'home.html',
controller: 'HomeController'
})
.state('about', {
url: '/about',
templateUrl: 'about.html',
controller: 'AboutController'
})
.state('contact', {
url: '/contact',
templateUrl: 'contact.html',
controller: 'ContactController'
})
.state('notFound', {
url: '/404',
templateUrl: '404.html',
controller: 'NotFoundController'
});
// Fallback Route - If the user enters an invalid URL
$urlRouterProvider.otherwise('/404'); // Default to 404 page if no route matches
});
Step 3: Create Views for Each State
Let’s now create basic HTML views for each state.
- home.html
<div>
<h1>Welcome to the Home Page!</h1>
<p>This is the home page of our application.</p>
</div>
- about.html
<div>
<h1>About Us</h1>
<p>This page contains information about our application.</p>
</div>
- contact.html
<div>
<h1>Contact Us</h1>
<p>If you have any questions, feel free to reach out.</p>
</div>
- 404.html (for the 404 Page)
<div>
<h1>404 - Page Not Found</h1>
<p>Sorry, the page you're looking for doesn't exist.</p>
<a href="#/home">Go Back to Home</a>
</div>
Step 4: Define Controllers for the Views
Now, let’s create simple controllers for each view in app.js.
app.controller('HomeController', function($scope) {
$scope.message = "Welcome to the Home Page!";
});
app.controller('AboutController', function($scope) {
$scope.message = "This is the About Page!";
});
app.controller('ContactController', function($scope) {
$scope.message = "This is the Contact Page!";
});
app.controller('NotFoundController', function($scope) {
$scope.message = "Sorry, this page doesn't exist!";
});
Step 5: Implementing the Default Route
To handle a default route, we use $urlRouterProvider.otherwise()
method, which redirects to a fallback URL when a user tries to visit a non-existent route.
In this example, we’ve set the fallback route to /404
, which will redirect users to the 404 page if they enter an invalid URL. Here’s the code in the config block:
$urlRouterProvider.otherwise('/404'); // Redirect to the 404 page if the URL is invalid
Step 6: Testing the Application
Now that we have defined the default routes and the 404 page, test your application by entering different URLs:
/home
– Should show the home page./about
– Should show the about page./contact
– Should show the contact page./anything-else
– Should redirect to the 404 page since this route is undefined.
Step 7: Adding More Advanced Error Handling (Optional)
If you want to handle more complex scenarios (e.g., redirecting users based on roles or other conditions), you can use the resolve
property in UI Router to perform checks before rendering the view. This could involve checking if a user is authenticated or if they have access to a particular page. If the check fails, you can redirect them to the appropriate page, like the login or home page.
Example with Role-based Redirection:
You can resolve an authentication service before loading the route:
$stateProvider
.state('dashboard', {
url: '/dashboard',
templateUrl: 'dashboard.html',
controller: 'DashboardController',
resolve: {
auth: function(AuthService, $state) {
if (!AuthService.isAuthenticated()) {
$state.go('login'); // Redirect if not authenticated
}
}
}
});