Introduction
In AngularJS, by default URL routes are added with a hashtag.
For example:
We are having a site as: http://sample.com/
When we click on About Us page, it redirects to http://sample.com/#/about
When we click on Contact Us page, it redirects to http://sample.com/#/contact
Below is the code that gives us the output as above examples:
var MyAppSample = angular.module('MyApp', []);
MyAppSample.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl : 'partials/home.html',
})
.when('/about', {
templateUrl : 'partials/about.html',
})
.when('/contact', {
templateUrl : 'partials/contact.html',
});
});
Now we want to remove the "#" from the URLs, no matter whichever section we want to access, # should not be visible in URL.
Steps to Remove # Tagging from URL
1. Configuring $locationProvider
In Angular, the $location
service parses the URL in the address bar and makes changes to your application and vice versa.We need to pass $locationProvider
as below:
var MyAppSample = angular.module('MyApp', []);
MyAppSample.config(function ($routeProvider, $locationProvider)
{
$routeProvider
.when('/', {
templateUrl : 'partials/home.html',
})
.when('/about', {
templateUrl : 'partials/about.html',
})
.when('/contact', {
templateUrl : 'partials/contact.html',
});
});
2. Set the HTM5 Mode to True
var MyAppSample = angular.module('MyApp', []);
MyAppSample.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl : 'partials/home.html',
})
.when('/about', {
templateUrl : 'partials/about.html',
})
.when('/contact', {
templateUrl : 'partials/contact.html',
});
});
Now a question may come to your mind that "What is the HTML5 History API"?
Well, it is a standardized way to manipulate the browser history using a script. This lets Angular change the routing and URLs of our pages without refreshing the page.