Monday, October 5, 2015

Remove hash # from url in angular js

The $location is a service component in AngularJs. This is what will be used to remove the hash from the urls. In the config function where the routing is done, inject the $location variable and set the html5Mode to true.

var app = angular.module('mainCtrl', ['ngRoute'])
            .config(config)
            .run(run);

config.$inject = ['$routeProvider', '$locationProvider'];
    function config($routeProvider, $locationProvider) {      

        $routeProvider
        .when( '/', {
            templateUrl: 'views/login.view.html'
        })

        .when( '/home', {
            templateUrl: 'views/home.html',
            controller: 'HomeCtrl'
        })

        .otherwise({
            redirectTo: '/'
        });

        $locationProvider.html5Mode(true);
    };

For this to work, you will have to set the base url. This can be done by putting the  in the head of the html file. Remember to include the name of the folder if you have all the files in a folder. Example: 

That will remove the hash from the urls.

No comments: