Migrating AngularJS html5mode links to Cordova

Gainstrack is implemented both for the desktop and for mobile – a true hybrid app. 90% of the code and views are shared with 10% having to be specifically customised.

One key difference is that a desktop AngularJS app looks much better with html5mode enabled so that URLs look natural without the # character. However, Cordova apps must have html5mode disabled. Thus links in vanilla <a href=”/foo”> tags would only work on one platform or the other but not both (only desktop in this case). It can be worked around by having links on both platforms like <a href=”#/foo”> and disabling html5mode link rewriting on the desktop side. However, clicking such a link on the desktop side would cause a page reload while Angular removes the #.

After hours of trying different solutions including Grunt building two different targets, trying to get html5mode working on Cordova, creating a urlFor method to put links in, in the end this simple snippet solved all problems on the mobile side.

angular.module('Gainstrack').directive('a', function() {
  return {
    priority: 1,
    restrict: 'E',
    link: function($scope, $element, $attrs) {
      $attrs.$observe('href', function (value) {
        if (value && value.indexOf('/') === 0) {
          $attrs.$set('href', '#' + value);

With this snippet only on the mobile side javascript, vanilla html5mode links are rewritten to hashbang links as required on the mobile side. Problem solved

Leave a Reply

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