Thursday, March 17, 2016

Angular translate in few steps

Next steps allow you to introduce i18n and l10n support to your frontend application.
First of all download angular-translate.js (also for no bower use) from https://angular-translate.github.io/

You can download directly last source code zip you found. Explode it in and put directly the angular-translate.js or the angular-translate.min.js in your WebContent dir.
Then import it into your html code with this:

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

In my case all the code needed for the translation has been moved into a separeted file....

<script src="js/translations.js"></script>

This is its content:

angular.module('shoppingListApp').config(function($translateProvider) {
      $translateProvider.translations('en', {
        APP_TITLE: 'SHOPPING LIST',
        ADD_ITEM_TEXT: 'Add shopping items here...'
      }).translations('it', {
        APP_TITLE: 'LA TUA SPESA!!',
        ADD_ITEM_TEXT: 'Aggiungi un nuovo articolo...'
      });
      $translateProvider.preferredLanguage('en');
    });



Now in my html file(or js code)......

<span>{{ 'APP_TITLE' | translate }}</span>

and.....

<span>({{ 'ADD_ITEM_TEXT' | translate }}</span>

do what you need....

The last three things:
1) This instruction

$translateProvider.preferredLanguage('en');

set what's the starting language to use



2) This instruction avoids xss(cross-site scripting) dangers for your application, as you can see http://angular-translate.github.io/docs/#/guide/19_security
// Enable escaping of HTML
$translateProvider.useSanitizeValueStrategy('escape');


3)Change at runtime your app language(defining the changeLanguage function in the controller..... and calling it..:-)): 

app.controller('TranslateController', function($translate, $scope) {
  $scope.changeLanguage = function (langKey) {
    $translate.use(langKey);
  };
});
 
 Please refer here for complete documentation: 
That's all.
Bye
 

No comments:

Post a Comment