January 12, 2016

AngularJS - Internationalization

To add internationalization to our demo app we can use a third-party module called angular-translate, you can download from https://github.com/angular-translate/bower-angular-translate/releases. I will add two text labels with language translations, English-Language, Arabic-Language and Urdu-Language.

A sample output of this demo will be like this:

With Arabic-Translator:

With Urdu-Translator:

With English-Translator:

First, we need to load the script in html page, so that AngularJS can find the module. Add following script tag in html page's head tag:

<script src="assets/libs/angular-translate.min.js"></script>

Next we have to add a dependency on the module pascalprecht.translate defined in angular-translate. So, we go to our main app module and add pascalprecht.translate module in the dependencies list. It now looks like this:
var demoApp = angular.module('demoApp', ['pascalprecht.translate']);
Now, we need to add $translateProvider dependency in the config function of our main module demoApp. Then we add translations for the languages we required in our application. In this demo I am using English-Language, Arabic-Language and Urdu-Language. The following code shows how it's done:
demoApp.config(['$translateProvider', function ($translateProvider) {

    $translateProvider.translations('ar', {
        TITLE: 'تدويل تجريبي',
        DESCRIPTION: 'يمكننا استخدام وحدة خارجية، angular-translate ، إضافة إلى تدويل التطبيق التجريبي لدينا.',
    });

    $translateProvider.translations('ur', {
        TITLE: 'بین الاقوامیت سازی ڈیمو',
        DESCRIPTION: 'ہم ڈیمو اپلی کیشن کے لئے عالمگیریت شامل کرنے کے لئے، angular-translate ، ایک تیسری پارٹی کے ماڈیول کا استعمال کر سکتے ہیں.'
    });

    $translateProvider.translations('en', {
        TITLE: 'Internationalization Demo',
        DESCRIPTION: 'We can use a third-party module, angular-translate, to add internationalization to our demo app.'
    });

    $translateProvider.preferredLanguage('en');
}]);

We use translateProvider.translations to add the translations against a key. Here we added translations for English, Arabic and Urdu languages. If you want to support more languages you can keep adding more translations in the same way. Finally, we set the preferred language to English by calling function$translateProvider.preferredLanguage('en').

Next, we'll add options in html page to let user switch between available languages, so we add a toggle button to html page using bootstrap. The following markup do this work:

<div class="btn-group btn-toggle">
 <button class="btn btn-xs btn-default"
  ng-class="{ar:'active'}[languagePreference.currentLanguage]"
  ng-click="languagePreference.switchLanguage('ar')">
  Arabic</button>

 <button class="btn btn-xs btn-default"
  ng-class="{de:'active'}[languagePreference.currentLanguage]"
  ng-click="languagePreference.switchLanguage('ur')">
  Urdu</button>

 <button class="btn btn-xs btn-default"
  ng-class="{en:'active'}[languagePreference.currentLanguage]"
  ng-click="languagePreference.switchLanguage('en')">
  English
 </button>
</div>
The next thing we need to do is add a function languagePreference.switchLanguage() to $rootScope, which we called in the above markup for toggle button's click event. This accepts a language key and sets the specified language a variable named languagePreference.currentLanguage, used in the above markup in ng-class attribute to setup view for the selected language by applying active class. For that we need to modify the run block in our demoApp module as follows:

demoApp.run(['$rootScope', '$translate', function ($rootScope, $translate) {
    
    $rootScope.languagePreference = { currentLanguage: 'en' };
    $rootScope.languagePreference.switchLanguage = function (key) {

        $translate.use(key);
        $rootScope.languagePreference.currentLanguage = key;
    }

}]);

The function $translate.use(key) takes a key and loads the translations written against it, that we defined in the config function.

Now comes the final thing, to use this translator in UI. We need to replace the static hardcoded strings with a call to translate filter.

For example, regular text will go like this:

<h3>{{'TITLE'}}</h3>
<p>{{'DESCRIPTION'}}</p>
After adding translate filter, the final html will become like this:
<h3>{{'TITLE' | translate}}</h3>
<p>{{'DESCRIPTION' | translate}}</p>
Thats it. We have setup a simple html page with two strings, i.e. TITLE and DESCRIPTION, that will be displayed in three different languages. Similary you can add more language translations in the config function if you need. Also the same way you can add more html text with translate filter where required.

5 comments:

  1. In recent days Angular plays vital role to loading your site content in a fastest way, so it’s a required skill for everyone, thanks for sharing this useful information to our vision keep blogging.
    Regards,
    Angularjs training in chennai|Angularjs training chennai

    ReplyDelete
  2. The oracle database is capable of storing the data in two forms such as logically in the form of table spaces and physically like data files.
    Oracle Training in Chennai | oracle dba training in chennai

    ReplyDelete

  3. Very informative content that guided me to know the details about the training offered in different technology. Angular JS is a structural framework for dynamic web application and angular's data binding eliminates much of the code that you would otherwise write it.
    Angularjs Training in Chennai | angularjs course in chennai

    ReplyDelete
  4. Great and useful article. Creating content regularly is very tough. Your points are motivated me to move on.


    Angularjs 2 Development Company




    ReplyDelete
  5. Hi there! For those who need to translate their application into multiple languages, I recommend evaluating a software localization tool like POEditor, because it can save time and improve the workflow.

    ReplyDelete