Internationalisation & Localisation in AngularJS

Set up AngularJS projects to be translated using html template tags. This post looks at how you can use the Angular libraries plus a custom filter to ensure content is contextualised to the user.




Internationalisation
Adapting a product to match common time/currency/data patterns. It is often shortened to i18n, where 18 is the number of letters between i and n in the English word.

Localisation
Adapting a product to match specific language/dialect/cultural situations. It is often shortened to l10n, where 10 is the number of letters between l and n in the English word.

So how to go about adding support for this to AngularJS?

Firstly you will need to download the predefined locale files to a i18n folder:
https://github.com/angular/angular.js/tree/master/src/ngLocale

Then you need to create your own l10n folder which contains an angular-translate_fr-fr.js file with the following:

angular.module('ngTranslate', [], ['$provide', function ($provide) {
    $provide.value('$translate', {
        "This is english title": "This is french title"
    });
}]);

And then you need to create a filter at js/filters/translate.js which contains:

angular.module('app.filters.translate', ['ngTranslate'])
    .filter('translate', ['$translate', function ($translate) {
        return function (key) {
            return $translate[key] || key;
        };
    }]);

Then include the files on your index.html:

<script src="lib/angular.js"></script>
<script src="i18n/angular-locale_fr-fr.js"></script>
<script src="l10n/angular-translate_fr-fr.js"></script>
<script src="js/filters/translate.js"></script>

Now you can use the translate filter to translate a string using the following format in your html templates:

<h2>{{ 'This is english title' | translate }}</h2>

Here is a fiddle showing the example working end-to-end:

No comments:

Post a Comment