Click here to Skip to main content
15,923,845 members
Articles / AngularJs
Tip/Trick

Removing "#" From URL in AngularJS

Rate me:
Please Sign up or sign in to vote.
4.33/5 (2 votes)
7 Oct 2014CPOL 36.6K   8  
Removing "#" From URL in AngularJS

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:

C#
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:

C#
var MyAppSample = angular.module('MyApp', []);
    
MyAppSample.config(function ($routeProvider, $locationProvider) 
{  //Notice here i have passed location provider

    $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

C#
var MyAppSample = angular.module('MyApp', []);
    
MyAppSample.config(function ($routeProvider, $locationProvider) {
    
    // use the HTML5 History API & set HTM5 mode true
    $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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --