Localization

As worldwide access to the web increases, we as developers are constantly pressed to make our apps internationally and locally accessible. When a user visits our apps, he or she should be able to switch languages on the fly at run time.

Given that we are building AngularJS client-side apps, we don’t particularly want the user to have to refresh the page or visit an entirely different URL. Of course, AngularJS could easily accommodate your international audience natively, perhaps by generating different templates for different languages and serving those within the app.

This process can become cumbersome, however, and what happens when we want to change the layout of the app? Every single template needs to be rebuilt and redeployed. This process should just be easy.

angular-translate

Instead of creating new templates, we can use angular-translate, an AngularJS module that brings i18n (internationalization) to your Angular app. angularjs-translate requires us to create a JSON file that represents translation data per language. It lazy loads the language-specific translation data from the server only when necessary.

The angular-translate library comes with built-in directives and filters that make it simple to internationalize our apps. Let’s get started.

Installation

To use angular-translate, we need to load the library. We can install it in several different ways, but we prefer using Bower.

Bower is a front-end package manager. It handles not only JavaScript libraries, but also HTML, CSS, and image packages. A package is simply encapsulated, third-party code that is typically publicly accessible in a repository.

We install angular-translate using the normal Bower process:

$ bower install angular-translate

Alternatively, we can download the minified version of angular-translate from GitHub.

Once we’ve installed the latest stable version of angular-translate, we can simply embed it in our HTML document. Just make sure it’s embedded after Angular itself, as it depends on the core angular library.

<script src="path/to/angular.js"></script>
<script src="path/to/angular-translate.js"></script>

Last but not least, our app has to declare angular-translate as a load dependency:

var app = angular.module('myApp', ['pascalprecht.translate']);

Great! Now we’re ready to use angular-translate’s components to translate our app.

Teaching Your App a New Language

Our app depends upon angular-translate as installed, and our app declares it as a dependency, so we can use it to translate our app’s contents.

First, we need to provide translation material so our app can actually speak a new language. This step entails configuring the $translate service through our fresh $translateProvider service.

Training our app to use a new language is simple. Using the config function on our app, we provide the different language translations for our app (i.e., English, German, Hebrew, etc.). First, we inject our $translateProvider in the config function, like so:

angular.module('angularTranslateApp', ['pascalprecht.translate'])
.config(function($translateProvider) {
  // Our translations will go in here
});

To add a language, we have to make $translateProvider aware of a translation table, which is a JSON object containing our messages (keys) that we will translate into values. Using a translation table enables us to write our translations as simple JSON for loading remotely or setting at compile time, such as:

{
  'MESSAGE': 'Hello world',
}

In a translation table, the key represents a translation ID, whereas the value represents the concrete translation for a certain language. Now we add a translation table to your app. $translateProvider provides a method called translations() to take care of that.

app.config(function($translateProvider) {
  $translateProvider.translations({
    HEADLINE: 'Hello there, This is my awesome app!',
    INTRO_TEXT: 'And it has i18n support!'
  });
});

With this translation table in place, our app is set to use angular-translate. Since we’re adding the translation table at configuration time, angular-translate’s components are able to access it as soon as they are instantiated.

Let’s switch over to our app template. Adding translations in the view layer is as simple as binding our key to the view. Using the translate filter, we don’t even have to engage our controller or services or worry about the view layer: We’re able to decouple the translate logic from any controller or service and make our view replaceable without touching business logic code.

Basically, the translate filter works like so:

<h2>{{ 'TRANSLATION_ID' | translate }}</h2>

To update our example app, we make use of the translate filter:

<h2>{{ 'HEADLINE' | translate }}</h2>
<p>{{ 'INTRO_TEXT' | translate }}</p>

Great! We’re now able to translate our content within the view layer without polluting our controllers’ logic with translation logic; however, we could achieve the same result without using angular-translate at all, since our app only knows about one language.

Let’s see angular-translate’s real power and learn how to teach our app more than one language.

Multi-language Support

We’ve already added a translation table to the app via the translations() method.

The $translateProvider knows one language, as we set it with the translations() method. Now, we can add an additional language in the same way by providing a second translation table.

When we set our first translation table, we can provide it a key (a language key) that specifies the language we’re translating. We can simply add another translation key with another language key.

Let’s update our app to include a second language:

app.config(function($translateProvider) {
  $translateProvider.translations('en_US', {
    HEADLINE: 'Hello there, This is my awesome app!',
    INTRO_TEXT: 'And it has i18n support!'
  });
});

To add a second translation table for another language, let’s say German, we want to just do the same with a different language key:

app.config(function($translateProvider) {
  $translateProvider.translations('en_US', {
    HEADLINE: 'Hello there, This is my awesome app!',
    INTRO_TEXT: 'And it has i18n support!'
  })
  .translations('de', {
    HEADLINE: 'Hey, das ist meine großartige App!',
    INTRO_TEXT: 'Und sie untersützt mehrere Sprachen!'
  });
});

Now our app knows about two different languages. We can add as many languages as needed – there’s no limit; however, since there are now two languages available, how does our app know which language to use? angular-translate doesn’t prefer any language until you tell it to do so.

To set a preferred language, we can use the method $translateProvider.preferredLanguage(). This method tells angular-translate which of the registered languages is the one that our app should use by default. It expects an argument with the value of the language key, which points to a certain translation table.

Now, let’s tell our app that it should use English as its default language:

app.config(function($translateProvider) {
  $translateProvider.translations('en', {
    HEADLINE: 'Hello there, This is my awesome app!',
    INTRO_TEXT: 'And it has i18n support!'
  })
  .translations('de', {
    HEADLINE: 'Hey, das ist meine großartige App!',
    INTRO_TEXT: 'Und sie untersützt mehrere Sprachen!'
  });
  $translateProvider.preferredLanguage('en');
});
 
This page is a preview of ng-book.
Get the rest of this chapter plus 600 pages of the best Angular content on the web.

 

Ready to master AngularJS?

  • What if you could master the entire framework – with solid foundations – in less time without beating your head against a wall? Imagine how quickly you could work if you knew the best practices and the best tools?
  • Stop wasting your time searching and have everything you need to be productive in one, well-organized place, with complete examples to get your project up without needing to resort to endless hours of research.
  • You will learn what you need to know to work professionally with ng-book: The Complete Book on AngularJS or get your money back.
Get it now