Monday 14 April 2014

Dynamic locale in AngularJS

As soon as one starts to deal with a multilingual application in AngularJS, he is faced with the fact that the $locale service is a read-only service.

As a end user of the application, I want to select the language I'm working with, and see the changes to the screen immediately applied.

In particular, I was also using the excellent angular-translate module for having my labels translated. I could change my locale for the translation module using $translate.use(locale), but the AngularJS locale itself was not changed - this made localised dates & times using the former selected locale. Very not good.

Here is the solution I have found for switching the language.

In the main module file, I add, before the module declaration, a detection of the current locale. In my case, I chose to store it locally, but it could be any other mechanism:

// Local storage for the locale
if (console) console.log('[language] Checking language on load');
var language = localStorage['iteachLanguage'];
if (!language) {
    if (console) console.log('[language] No language specified, using "en"');
    language = 'en';
}
if (console) console.log('[language] Using ' + language);

Then, in the module loading itself, I load the corresponding ngLocale module (which are available though the angular-locale_**.js file distributed with Angular - pity they are not available yet through Bower):

angular.module('myapp', [
            'ui.bootstrap',
            'ui.calendar',
            'ngRoute',
            'ngSanitize',
            'ngLocale_' + language,
            'pascalprecht.translate',
            ...

Then, when the user selects a locale, I just have to store it locally and reload the page:

$scope.changeLanguage = function (lang) {
   localStorage['iteachLanguage'] = lang;
   location.reload();
};

Well, yes, I have to reload the page... But in such a case, I think this is acceptable.

2 comments:

  1. In addition to learning angularjs at online Angularjs training, this blog adds to my learning platforms. Great work done by the website owner. Thanks for your in depth research and experience sharing on this website.

    ReplyDelete