Reputation: 1781
Implementing i18n isn't very difficult when you have a list of json documents stored on the client. But what if you can't have the json files stored locally? They have to be retrieved at runtime. What is the best way to achieve this.
I thought about storing them in sessionStorage as they are required but how do I get angular-translate to work with that or something similar?
When I work with local files I simply point to their location:
urlTemplate: 'assets/translation/{lang}/{part}.json'
Upvotes: 1
Views: 3446
Reputation: 181
I don't know if this is the best way, but I have been using the static files loader from angular-translate for this.
Let's say you have a folder full of translation files:
locales/locale-de_DE.json
locales/locale-en_GB.json
locales/locale-nl_BE.json
...
Then in your app, you would do this:
var app = angular.module('myApp', [ ]);
app.config([ '$translateProvider',
function($translateProvider) {
$translateProvider.useStaticFilesLoader({
prefix: 'locales/',
suffix: '.json'
});
}
]);
app.run([ '$translate',
function($translate) {
// Set default language to German
$translate.use('locale-de_DE');
}
]);
Whenever you want to switch the language later on in your code, you just need to call the $translate-service with the language you want to switch to, e.g.
[...]
$translate.use('locale-en_GB'); // switch to British English
[...]
Upvotes: 1