By default, AngularJS
uses hash(#) in the URLs for routing.
For instance:
http://example.com/
http://example.com/#/about
http://example.com/#/contact
To eliminate the hashtag from the URL, two steps are required:
- Setting up
$locationProvider
- Configuring the base for relative links
Utilizing $location Service
In AngularJS, the $location
service decodes the URL in the address bar and manages changes to the application accordingly.
Implementing $locationProvider and html5Mode
The $locationProvider
module will be used along with setting html5Mode
to true.
This process occurs during Angular application definition and route configuration.
angular.module('stackoverflow', [])
.config(function($routeProvider, $locationProvider) {
$routeProvider
.when('/', {
templateUrl : 'partials/home.html',
controller : homeController
})
.when('/about', {
templateUrl : 'partials/about.html',
controller : aboutController
})
.when('/contact', {
templateUrl : 'partials/contact.html',
controller : partialController
});
// utilize the HTML5 History API
$locationProvider.html5Mode(true);
});
Establishing Relative Links
To navigate within the application using relative links, it is essential to include a <base>
element in the <head>
section of your document.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<base href="/">
</head>
There exist various methods for configuring this setup, and having the HTML5
mode enabled will automatically resolve relative links.