CaptSaltyJack
CaptSaltyJack

Reputation: 16045

Angular - how to stop using hash links to navigate?

Bear with me, I'm new to Angular.

I used the yeoman angular generator to scaffold a project. I've got this in my navigation:

    <ul class="nav nav-pills pull-right">
      <li class="active"><a ng-href="/">Home</a></li>
      <li><a ng-href="#/about">About</a></li>
      <li><a ng-href="#">Contact</a></li>
    </ul>

I don't like having the hashes in there, because when the site goes live, I don't want links to look like http://example.com/#/about. But if I change the above to:

<a ng-href="/about">About</a></li>

The page breaks when I try to hit the About page. Here's what's in app.js:

angular
  .module('wowApp', [
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch'
  ])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .when('/about', {
        templateUrl: 'views/about.html',
        controller: 'AboutCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  });

Upvotes: 1

Views: 251

Answers (1)

David Barker
David Barker

Reputation: 14620

You need to configure $locationProvider to enable HTML5 mode.

angular
    .module('wowApp', [
        'ngAnimate',
        'ngCookies',
        'ngResource',
        'ngRoute',
        'ngSanitize',
        'ngTouch'
    ])
    .config([
        '$locationProvider',
        '$routeProvider',
        function ($locationProvider, $routeProvider) {
            // Set HTML 5 mode to true to disable #
            // in push states
            $locationProvider.html5Mode(true);

            // Setting HTML5 mode to true also requires
            // you to set a base URL for the application
            // or disable `requireBase`. If you don't need base
            $locationProvider.html5Mode({
                enabled : true,
                requireBase : false
            });


            $routeProvider.when(/* route logic as normal */);    
        }
    ]);

Reference for $locationProvider

Now you can remove the #'s from your anchors href values.

Upvotes: 1

Related Questions