AngularJS and Yeoman with the HTML5 History API

By default the Angular Generator for Yeoman isn’t set up for the HTML5 History API. Enabling it will make our routes look like https://example.com/register instead of https://example.com/#!/register.

We can enable it by putting the following snippet of code in the .config. section of app.js.

if (window.history && window.history.pushState) {
  $locationProvider.html5Mode(true);
}

We’ll also need to inject the $locationProvider service, so make sure your .config function accepts $locationProvider as an argument.

Here’s what the default app.js looks like after these changes.

'use strict';

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

    if (window.history && window.history.pushState) {
      $locationProvider.html5Mode(true);
    }
  });

When we serve the website, we’re going to need to always serve index.html regardless of the URL requested, leaving the routes for Angular to process.

To make this change in our development server (run with grunt serve), we’re going to need to make the following change to the connect section of our Gruntfile.

connect: {
  options: {
    ...
    middleware: function (connect, options) {
      var optBase = (typeof options.base === 'string') ? [options.base] : options.base;
      return [require('connect-modrewrite')(['!(\\..+)$ / [L]'])].concat(optBase.map(function(path){ return connect.static(path); }));
    }
  },
  ...
}

We’re also going to need to install connect-modrewrite and save it in our package.json. We can do this with the following command.

npm install connect-modrewrite --save-dev

Now we can run grunt serve and everything should be fine and dandy.

 
68
Kudos
 
68
Kudos