AngularJS routing is a powerful feature that allows you to build single-page applications (SPAs) by dynamically changing the content of a web page without reloading the entire page. It enables you to create a seamless user experience by providing smooth transitions between different views or pages within your application.
To use routing in AngularJS, you need to include the `ngRoute` module in your application. This module provides the necessary directives and services for routing.
Here are the steps to build a single-page application using AngularJS routing:
1. Include the `angular-route.js` file in your HTML file. This file contains the `ngRoute` module.
html
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.9/angular-route.js"></script>
2. Add the `ngRoute` module as a dependency in your AngularJS application.
javascript
var app = angular.module(‘myApp’, [‘ngRoute’]);
3. Configure the routes for your application using the `$routeProvider` service. This service allows you to define the URL patterns and the corresponding templates and controllers for each route.
javascript
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: ‘/’
});
});
In the above example, we have defined three routes: `/`, `/about`, and `/contact`. Each route is associated with a template file and a controller.
4. Create the template files for each route. These files will contain the HTML markup for the corresponding views.
html
<!– home.html –>
<h1>Welcome to the Home Page</h1>
<!– about.html –>
<h1>About Us</h1>
<!– contact.html –>
<h1>Contact Us</h1>
5. Create the controllers for each route. These controllers will handle the logic and data for each view.
javascript
app.controller(‘HomeController’, function($scope) {
// Controller logic for the home view
});
app.controller(‘AboutController’, function($scope) {
// Controller logic for the about view
});
app.controller(‘ContactController’, function($scope) {
// Controller logic for the contact view
});
6. Finally, add the `ng-view` directive to your HTML file. This directive acts as a placeholder for the content of the current route.
html
<div ng-view></div>
With these steps, you have successfully set up routing in your AngularJS application. Now, when a user navigates to different routes, the corresponding templates will be loaded into the `ng-view` directive, and the associated controllers will be executed.
AngularJS routing provides additional features like route parameters, nested routes, and route resolve, which allow you to create more complex and dynamic single-page applications.