Removing # Tag in the AngularJs Project url

In the last tutorial we have seen there happened to be a change in the url. The url changed from http://127.0.0.1:58586/index.html to http://127.0.0.1:58586/index.html#/ . This change is because of the introduction of the ui-router and its default state mechanisms. By default ui-router uses # tag for navigation and this behavior needs to be overridden. To bring back to the normal url without # tag we need to implement the following steps.

  • Include <base href=”/”> inside <head></head> of index.html
  • Add the below code in the config block
    app.config(function($stateProvider,$urlRouterProvider, $locationProvider){     $locationProvider.html5Mode(true);     $urlRouterProvider.otherwise('/index.html');    $stateProvider         .state('home',{             url:'/index.html',             templateUrl: '/templates/home.html'         }); });

Now hit http://127.0.0.1:58586/index.html in your browser and you see that the # tag is removed. Awesome right.

Ok lets understand what the above code does. We have included tag and hrefed “/” to indicate that relative links should start with “/” for all the urls form this application. Then we move on the config block where we have introduced or injected two new inbuilt services $urlRouterProvider and $ locationProvider.

Setting html5Mode to true relies on the history.pushState and helps rewrite the urls on the fly by doing this will eliminate the # tag provided by the ui-route. This api is exposed via angular’s inbuilt service $ locationProvider.

Similarly, in simple terms $urlRouterProvider. otherwise (“DEFAULT STATE”) specifies the default state. In our case we have instructed the default case to /index.html which is nothing but the home state.

This # tag removal is very important if you planning to do search engine optimization to make your site ranked better.

Download Demo

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *