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:

angularjs-internationalization-arabic

With Urdu-Translator:

angularjs-internationalization-urdu

With English-Translator:

angularjs-internationalization-english

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. Similarly 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.

22 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. 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
  3. This is such a good post. One of the best posts that I\'ve read in my whole life. I am so happy that you chose this day to give me this. Please, continue to give me such valuable posts. Cheers!
    Microsoft Azure online training
    Selenium online training
    Java online training
    Python online training
    uipath online training

    ReplyDelete
  4. This is most informative and also this post most user friendly and super navigation to all posts. Thank you so much for giving this information to me. AngularJS Course in Pune

    ReplyDelete
  5. Thanks for sharing your innovative ideas to our vision. I have read your blog and I gathered some new information through your blog. Your blog is really very informative and unique. Keep posting like this. Awaiting for your further update.If you are looking for Angular Applications In Australia, .Net Core Applications In New Zealand, IOT Applications In Singapore and .Net Applications In UAE information please visit our website Sidhyati Technology Solutions Pvt Ltd

    ReplyDelete
  6. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    I am really happy with your blog because your article is very unique and powerful for new.
    Best Training Institute for AWS in Pune
    Robotic Process Automation Training in Pune
    AngularJS Course in Pune

    ReplyDelete
  7. this is really good post here. Thanks for taking the time to post such valuable information. Quality content is what always gets the visitors coming.
    IELTS Coaching in chennai

    German Classes in Chennai

    GRE Coaching Classes in Chennai

    TOEFL Coaching in Chennai

    spoken english classes in chennai | Communication training

    ReplyDelete


  8. Nice article and thanks for sharing with us. Its very informative


    Machine Learning Training in Hyderabad

    ReplyDelete
  9. Nice blog...Very useful information is providing by ur blog..here is a way to find.
    Offshore Yii Development in India

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. Hi, Great information you will provide thanks for sharing this useful information and content.

    Best IAS Coaching in Delhi

    ReplyDelete
  12. AnonymousJune 23, 2023

    Your hard work and dedication are truly commendable. You consistently give it your all. Buy google drive storage pricing india from google drive storage pricing india

    ReplyDelete