Integrating AngularJS and i18n-js, Switching Locales at Runtime

AngularJS has really nice built-in support for number, currency and date formatting. Unfortunately it lacks two significant features:

  • Performing string lookup / interpolation via externalized message bundles, and
  • Allowing the application to change the current locale at runtime.

A colleague of mine recently recommended the i18n-js library for internationalization. i18n-js is a lightweight library (~700 lines) which implements string lookup and formatting and is a suitable replacement for Angular's localization libraries.

I've written a proof-of-concept showing how the two can be integrated and made the source available at Github. Below is an explanation of some of the key files. Some of the gists have been trimmed slightly to ease formatting on the page, so refer to Github for the full code.

The above adapter wraps the core i18n-js APIs and makes it easy to load message bundles for a given locale. I wanted this functionality to stand on its own, so note that there is no dependency on AngularJS itself in this file.

The code above goes in the root HTML page and is used to load the message bundles for the default locale and then bootstrap the Angular application. This ensures all bundles are finished loading before the Angular application inits. This can be important if some application modules require the translations or formatters to be ready during initialization.

The above snippet exposes the i18n-js functionality via a few straightforward AngularJS filters. If other application components require access ot the I18nAdapter itself, it would be easy to add a service or factory here to make the adapter injectable.

If you clone the Github repo and run it under a web server, you can see a very simple AngularJS app making use of this code. Enjoy!