Handling Internationalization (i18n) in AngularJS

Loading

Internationalization (i18n) is the process of making an application adaptable to different languages and regions. In AngularJS, i18n is implemented using built-in services and third-party libraries to support multi-language applications.

This guide will cover various techniques and best practices for handling internationalization in AngularJS applications.


1. Why Internationalization (i18n) is Important?

  • Expands global reach by supporting multiple languages.
  • Improves user experience for non-English speakers.
  • Ensures compliance with local laws and regulations in different regions.

2. Using AngularJS Built-in $locale Service

AngularJS provides a built-in $locale service for basic localization features like date, number, and currency formatting.

2.1 Changing the Locale Settings

AngularJS uses locale files from the angular-i18n package. You need to include the required locale file.

Step 1: Install Locale Files
Download and include the locale file for the desired language.

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-i18n/1.8.2/angular-locale_fr-fr.js"></script>

Step 2: Using $locale for Localization
Inject $locale into your controller to check the current locale settings.

app.controller("LocaleController", function($scope, $locale) {
$scope.currentLocale = $locale.id; // Example: 'fr-fr'
});

3. Using Angular Translate for Dynamic Language Switching

The angular-translate library is the most widely used solution for i18n in AngularJS. It allows dynamic language switching and text translations.

3.1 Install angular-translate

Include the angular-translate library via CDN or install using npm/bower.

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-translate/2.18.4/angular-translate.min.js"></script>

4. Configuring angular-translate

4.1 Adding Language Translations

Define translations using $translateProvider inside the AngularJS configuration block.

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

app.config(function($translateProvider) {
$translateProvider.translations("en", {
GREETING: "Hello!",
WELCOME_MESSAGE: "Welcome to our website"
});

$translateProvider.translations("fr", {
GREETING: "Bonjour!",
WELCOME_MESSAGE: "Bienvenue sur notre site Web"
});

// Set default language
$translateProvider.preferredLanguage("en");
});

4.2 Displaying Translations in HTML

Use the translate directive to display translated text dynamically.

<p translate="GREETING"></p>
<p translate="WELCOME_MESSAGE"></p>

This will show:

  • English: “Hello!”
  • French: “Bonjour!”

4.3 Switching Languages Dynamically

Create a dropdown to allow users to switch languages.

<select ng-model="selectedLang" ng-change="changeLanguage(selectedLang)">
<option value="en">English</option>
<option value="fr">French</option>
</select>

Define the function to update the language dynamically.

app.controller("TranslateController", function($scope, $translate) {
$scope.changeLanguage = function(langKey) {
$translate.use(langKey);
};
});

5. Using JSON Files for Translations

Instead of defining translations inside app.config, you can load them from an external JSON file.

Step 1: Create Language Files

  • locales/en.json { "GREETING": "Hello!", "WELCOME_MESSAGE": "Welcome to our website" }
  • locales/fr.json { "GREETING": "Bonjour!", "WELCOME_MESSAGE": "Bienvenue sur notre site Web" }

Step 2: Configure angular-translate to Load JSON Files

app.config(function($translateProvider) {
$translateProvider.useStaticFilesLoader({
prefix: "locales/",
suffix: ".json"
});

$translateProvider.preferredLanguage("en");
});

6. Formatting Dates and Currency Based on Locale

AngularJS provides filters like currency, date, and number to format values based on locale settings.

6.1 Formatting Dates

<p>{{ today | date:'fullDate' }}</p>
app.controller("DateController", function($scope) {
$scope.today = new Date();
});

6.2 Formatting Currency

<p>{{ price | currency }}</p>
app.controller("CurrencyController", function($scope) {
$scope.price = 1500;
});

If you load a French locale (angular-locale_fr-fr.js), it will automatically format the currency for France.


7. Pluralization and Dynamic Translations

7.1 Handling Pluralization

app.config(function($translateProvider) {
$translateProvider.translations("en", {
APPLE_COUNT: {
"one": "One apple",
"other": "{{count}} apples"
}
});

$translateProvider.preferredLanguage("en");
});

7.2 Using Pluralization in HTML

<p>{{ 1 | translate:'APPLE_COUNT' }}</p>
<p>{{ 5 | translate:'APPLE_COUNT' }}</p>
  • 1 apple
  • 5 apples

8. Storing User’s Preferred Language

To save the selected language across sessions, use localStorage.

app.run(function($translate) {
var lang = localStorage.getItem("language") || "en";
$translate.use(lang);
});

app.controller("LanguageController", function($scope, $translate) {
$scope.setLanguage = function(langKey) {
$translate.use(langKey);
localStorage.setItem("language", langKey);
};
});

9. Right-to-Left (RTL) Language Support

For languages like Arabic (ar), you need to add RTL support dynamically.

9.1 Detect and Apply RTL

app.controller("RTLController", function($scope, $translate) {
$scope.$watch(function() {
return $translate.use();
}, function(langKey) {
document.body.dir = langKey === "ar" ? "rtl" : "ltr";
});
});

9.2 CSS for RTL Languages

[dir="rtl"] {
direction: rtl;
text-align: right;
}

10. Testing and Debugging Translations

10.1 Debugging Missing Translations

Enable fallback text for missing translations:

$translateProvider.useMissingTranslationHandlerLog();

Leave a Reply

Your email address will not be published. Required fields are marked *