Last Updated: September 09, 2019
·
3.671K
· gerardsans

Angular - Internationalisation

AngularJs Meetup South London Collection | this article

Internationalisation using angular-translate

Internationalisation cover many topics. In this protip I will provide a basic skeleton to get started with angular-translate. Features shown in this protip:

- provide different languages using json objects (language table)
- language files will be loaded asynchronously using angular-translate extension *StaticFilesLoader*
- there will be a fallback language if a key is not found using the current language
- we will use a dropdown to let the user change the language

A working code is included at the end.

Setup

angular.module("myapp", ['pascalprecht.translate'])
.config(function ($translateProvider) {
    //default language
    $translateProvider.preferredLanguage('en');
    //fallback language if entry is not found in current language
    $translateProvider.fallbackLanguage('es');
    //load language entries from files
    $translateProvider.useStaticFilesLoader({
        prefix: '', //relative path Eg: /languages/
        suffix: '.json' //file extension
    });
})

Usages

Below you can see usage for the attribute directive and filter. Within a controller, you can use the $translate service.

<h1 translate="title"></h1>
<h1>{{title | translate}}</h1>

Language Selection

Below snippets for the language dropdown and controller.

<!-- html code -->
<select ng-model="selectedLanguage" ng-change="changeLanguage()">
  <option value="en" translate="global_language_en"></option>
  <option value="es" translate="global_language_es"></option>
</select>

//controller
.controller("Controller", function($scope, $translate) {
    //variable to store selected language
    $scope.selectedLanguage = $translate.proposedLanguage(); //default

    $scope.changeLanguage = function () {
      //use parameter needs to be part of a known locale Eg: en-UK, en, etc
      $translate.use($scope.selectedLanguage);
    };
});

Resources

angular-translate guide

Demo code: link

AngularJs Meetup South London Collection | this article