Internationalization with AngularJS

17 / Jul / 2015 by Dhiraj Sharma 0 comments

Why is internationalization support so important?

These days variety of web projects demand the support for multiple languages feature. Most of the internet users do not have English as their first language. Thus there is a need to reach those users as well. There are many modules available to achieve multilingual feature in AngularJs like angular-gettext, angular-translate. We’ll cover the basics of angular-translate, configurations with some examples.

What is angular-translate?

It is a module which helps to implement internationalization features in AngularJs. It provides us with components like filters, directives and functions to load i18n data asynchronously. It uses JSON format messages to achieve ease of implementation.

Configuration

You can use bower to install ‘angular-translate’ and ‘angular’.

bower install angular
bower install angular-translate

Here is the CDN link for angular and angular-translate:


https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.16/angular.min.js


https://cdnjs.cloudflare.com/ajax/libs/bower-angular-translate/2.7.1/angular-translate.min.js

 

Setting up your page

When setting up your page, you have to include angular.js and angular-translate.js file (index.html).

<div>
  <h3> Hello</h3>
  <p>This is a demo app for multilingual support.</p>
  <label>Click here for switching language between spanish to english </label>
  <button> Change</button>
</div>

 

Adding dependency in your app 

Inject ‘pascalprecht.translate’ module in your app:

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

 

 Configure $translateProvider in your app

MultilingualApp.config(function ($translateProvider) {
  $translateProvider.translations('US_EN', {
    'GREETING': 'Hello !',
    'DESCRIPTION': 'This is a demo app for multilingual support.',
    'LBL_SWITCH':'Click here for switching language between spanish to english',
    'CLICK': 'Click'
  });

  $translateProvider.translations('SPANISH', {
    'GREETING': 'Hola !',
    'DESCRIPTION': 'Esta es una aplicación de demostración para soporte multilingüe.',
    'LBL_SWITCH': 'Haga clic aquí para cambiar el idioma entre español al Inglés',
    'CLICK': 'Clic'
  });

//It sets default language for your app
$translateProvider.preferredLanguage('US_EN');
});

Add dependency in your controller

In your controller inject ‘$translate’ service.

MultilingualApp.controller('MyCtrl', function ($scope, $translate) {
  $scope.changeLanguage = function () {
    var language = $translate.use();
    if (language === 'US_EN') {
      $translate.use('SPANISH');
    } else {
      $translate.use('US_EN');
    }
  };
});

 

$translate.use() : When it is called without parameter it is treated as getter function. It will return current key (language). If you pass parameter then it is acted like setter function and it will reset the language.
Your angular application should resemble to following piece of code:

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

MultilingualApp.config(function ($translateProvider) {
  $translateProvider.translations("US_EN", {
    "GREETING": "Hello !",
    "DESCRIPTION": "This is a demo app for multilingual support.",
    "LBL_SWITCH": "Click here for switching language between spanish to english",
    "CLICK": "Click"
  });
  $translateProvider.translations("SPANISH", {
    "GREETING": "Hola !",
    "DESCRIPTION": "Esta es una aplicacion de demostracion para soporte multilingue",
    "LBL_SWITCH": "Haga clic aquí para cambiar el idioma entre espanol al Ingles",
    "CLICK": "Click"
  });
  $translateProvider.preferredLanguage("US_EN");
});

MultilingualApp.controller("MyCtrl", function ($scope, $translate) {
  $scope.changeLanguage = function () {
    var language = $translate.use();
    if (language === "US_EN") {
      $translate.use("SPANISH");
    } else {
      $translate.use("US_EN");
    }
  };
});

Update  view

There are three ways to update your view to enable internationalization.

  • Using Filter
  • Using Directive
  • Using Service

Using Filter:

Update your view file using ‘translate’ filter. It will convert your static text into i18n messages.

<h3>{{'GREETING'|translate}} </h3>
will converted into
<h3> Hello</h3>

 

Using Directive:

<h3> <pre translate="GREETING"></pre></h3>
will translated into
 <h3> Hello</h3>

 

Using Service:

If you are using service to convert your static text into i18n messages. Then first you have to inject $translate service into your controller.

MultilingualApp.controller("MyCtrl", function ($scope, $translate) {
  $translate('GREETING').then(function (translation) {
    $scope.greetingText = translation;
   });
});

View should be look like this:

 <div ng-controller="MyCtrl"> <h3>{{greetingText}}</h3> </div>

 

Here I have used filter for enabling  view for internationalization which is mostly used.

<html>
<body>
<script src="angular.min.js"></script>
<script src="angular-translate.min.js"></script>
<script src="app.js"></script>
<div ng-app='MultilingualApp'>
    <div ng-controller='MyCtrl'>
        <h3>{{'GREETING'|translate}}</h3>
        <p>{{'DESCRIPTION'|translate}}</p>
        <label>{{'LBL_SWITCH'|translate}} </label>
        <button ng-click='changeLanguage()'> {{'CLICK'|translate}}</button>
    </div>
</div>
</body>
</html>

 

You can try it out yourself on JSFiddle multilingualDemoApp.

To learn more about angular-translate visit angular-translate.

 

Liked the blog and found it useful? I’d love to get your feedback!

Tag -

FOUND THIS USEFUL? SHARE IT

Leave a comment -