My Goal and Approach
Within our AngularJS application, we utilize angular-ui-bootstrap for datepickers. Our aim is to localize the datepickers based on the user's locale. However, dynamically changing the locale in AngularJS poses a challenge due to the lack of an API for such functionality. The user's locale information is retrieved from the backend, prompting the need to adjust Angular's locale before rendering the main state. To address this issue, I propose invoking a service that will inject the appropriate locale file into our application.
The Implementation
The injectorService:
;(function(module) {
'use strict';
function injector($q) {
var body = document.getElementsByTagName('body')[0];
return {
addScript: function(url, async, cb) {
return $q(function(resolve, reject) {
var script = document.createElement('script');
var loaded;
script.type = 'text/javascript';
script.setAttribute('src', url);
script.onreadystatechange = script.onload = function() {
if (!loaded) {
if(cb && _.isFunction(cb)){
cb(null, 'ok');
} else {
return resolve('ok');
}
}
loaded = true;
resolve('loaded');
};
script.onerror = function(error) {
if(!error.isTrusted){
if(cb && _.isFunction(cb)){
cb(error, null);
} else {
reject(error);
}
}
};
body.appendChild(script);
});
}
};
}
module.factory('Injector', injector);
}(angular.module('injector', [])));
In initializing the main state, the following code is called within the resolve section
resolve: {
env : function(userService, Injector) {
return userService.getLocale()
.then(function(env) {
var userEnv = env;
var baseUrl = '/app/';
var angularSpecificLocale = '';
switch(userEnv.userlocale){
case 'fr':
angularSpecificLocale = baseUrl + 'fr.js';
break;
case 'ro':
angularSpecificLocale = baseUrl + 'ro.js';
break;
default:
angularSpecificLocale = 'en';
break;
}
// Omit any locale files if set to English by default
if(angularSpecificLocale === 'en'){
return userEnv;
} else {
return Injector.addScript(angularSpecificLocale)
.then(function() {
return userEnv;
});
}
});
}
}
The Challenge
Despite my efforts, the datepicker remains unlocalized. It seems like there may be a missing step in the process. By adding the following snippet in my code:
angular.injector(['ngLocale']).get('$locale')
I can confirm that the locale id is correct. Any assistance without relying on external libraries would be greatly appreciated!
Thank you :)