May 2, 2013, angularjs, routing, html.
AngularJS: Changing App Path, and the <base> Element
Shows how to make Angular live happily at a non-root path (i.e. not at /
), and introduces the <base>
HTML element.
The Problem
So you’ve built an AngularJS app, kicked the tires using any one of a number of locally run web servers, and it’s time to put it live. You want the app to live somewhere other than the root of the domain /
— perhaps /firefly/
for example. What is the most DRY way to accomplish this?
Option One: Modify Routes
One possibility would be to modify your routes and add a prefix to all paths:
angular.module('app').config(function ($routeProvider) { var site_prefix = '/firefly'; $routeProvider. when(site_prefix + '/', { controller: HomeCtrl, templateUrl: 'partials/home.html' }). when(site_prefix + '/serenity', { controller: SerenityCtrl, templateUrl: 'partials/serenity.html' }); });
This is slightly verbose, and decreases the readability of your routing logic. Is there another option?
Option Two: The <base>
Element
From the W3C HTML Working Draft:
“The base element specifies a document-wide base URL for the purposes of resolving relative URLs, and a document-wide default browsing context name for the purposes of following hyperlinks.”
Now we’re getting somewhere! This <base>
element allows us to use the following HTML markup to define a base URL that all of our relative links will be base on:
<html ng-app="app"> <head> <base href="/firefly/" /> ... </head> <body> <a href="serenity">Serenity!</a> </body> </html>
Bingo! Now we can use relative links everywhere, and Angular will be able to piece together the correct URL. Note that this works best with Angular’s HTML5 Mode, enabled by $locationProvider:
angular.module('app').config(function ($locationProvider) { $locationProvider.html5Mode(true); });
This disables the hashbang mode for modern browsers, and leverages the HTML5 History API. One downside of the <base>
element is that since all link paths are now interpreted as relative to the base’s href, hash tag links (e.g. <a href="#top">Top</a>
) will not work properly without some finagling. Possible remedies include altering the <base>
element on a page that has a lot of said hash tag links, or simply referencing an absolute url with the hash tag appended.