Simple to use Angular.js service & filter to be able to switch locale dynamically, with no need to do a full page refresh.
AngularJS use a multiple files approach to handle the internationalization. In that case, if you need to switch locale dynamically, you need a full page refresh to import the new locale file needed for the new language.
I want to share with you my approach on how I resolve the full page refresh using a custom filter and an angular service to handle the dictionary and the language switching.
If you find any bug in the product, or would like a feature implemented, use the issue tracker over at the GitHub repository.
Step 1: is to write your own i18nDictionary angular service.
This service is responsible to fetch/load the dictionary for a certain locale.
The only requirement, is that the result is a JSON object containing a list of KEY:VALUE pair.
Ex: {'myKey':'value1', 'my_Key2':'value2', 'my.key.3':'value3'};
In the repository, you'll find a i18nDictionary template example.
Step 2: Import the .JS files
Step 3:
When creating your angular app, just add i18nDynamic as a dependency.
Step 4:
Use the i18n filter in your template.
setLocale(newLanguage): To switch to a new locale.
newLanguage: any language string as defined by i18n convention ex: 'en', 'fr-ca', 'es', ...
Don't forget that your i18nDynDictionary implementation need to be able to load/fetch dictionary for this locale.
Key | Message |
key1 | {{"key1" | i18nDyn }} |
key2 | {{"key2" | i18nDyn }} |
key3 | {{"key3" | i18nDyn }} |
AngularJS date filter unaltered