Angular ui-router adding hash to url

Issue

I am setting up a scaffold for an app with angular and angular-ui-router. I have it working however it seems to be adding a hash into my url (I’m running dev on localhost) localhost:9000/#/test. When I land on the main page it’s just localhost:9000 and it still serves the main view content. I would like to get rid of the hash if possible.

So here is my setup:

In my index.html in the body I just have my nav and then the ui-view under that:

 <div class="row">
   <ul class="nav navbar-nav">
      <li><a ui-sref="index">Home</a></li>
      <li><a ui-sref="test">Test</a></li>
    </ul>
  </div>

  <div ui-view=""></div>

and in my app.js I just have:

angular
.module('playApp', [
'ui.router'
])
.config(function($stateProvider) {
$stateProvider
.state('index', {
    url: '',
    templateUrl: 'views/main.html',
    controller: 'MainCtrl'
})
.state('test', {
    url: '/test',
    templateUrl: 'views/test.html',
    controller: 'testCtrl'
});
});

So when I land, it’s fine, but when I start using the nav I have set up, it adds the hashes to the url, would prefer not to have them if possible. Thanks!

Solution

Include $locationProvider and do $locationProvider.html5Mode(true); :

angular.module('playApp', ['ui.router'])
    .config(function($stateProvider, $locationProvider) {
        $stateProvider.state('index', {
            url: '',
            templateUrl: 'views/main.html',
            controller: 'MainCtrl'
        })
       .state('test', {
            url: '/test',
            templateUrl: 'views/test.html',
            controller: 'testCtrl'
        });

        $locationProvider.html5Mode(true);
    });

I also have an otherwise in there as well, so that if it can’t find a specified route, it will just default back:

angular.module('playApp', ['ui.router'])
    .config(function($stateProvider, $locationProvider, $urlRouterProvider) {
        $stateProvider.state('index', {
            url: '',
            templateUrl: 'views/main.html',
            controller: 'MainCtrl'
        })
       .state('test', {
            url: '/test',
            templateUrl: 'views/test.html',
            controller: 'testCtrl'
        });

        $locationProvider.html5Mode(true);
        $urlRouterProvider.otherwise('/');
    });

Answered By – Callum Linington

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.