AngularJS and web application internationalization
Internationalization of web applications is ubiquitous and i show how can you make it in your application with AngularJS.
For example we have some *.json
files with our translations, something like this en_US.json
:
{
"en_US" : {
"HOME": "home",
"GREETINGS": "Hello, how are you?"
....
}
}
First of all we must to load our en_US.json
file and files with other translations and save it's content to the variable. I will load it in the initialization part of web application.
app.js
:
var Lang =
(function() {var json = null;
$.ajax({
'async': false,
'url': "/en_US.json",
success: function (data) {
json = JSON.parse(data);
}
});
return json;
})();
Now we can use Lang
variable everywhere. Let's create AngularJS
filter. We will transform content to necessary translation.
MyApplication.filter('translate', function (){
return function(input){
//
// Check necessary locale locale
//
// .....
//
// Change locale
//
for (var prop in Lang){
if (prop == input)
// return translation
return Lang[prop];
}
}
});
Now we can ease translate any content in our application. Use translate
filter in your templates like:
<div>{{ 'GREETINGS' | translate }}
<p>{{ 'HOME' | translate }}</p>
</div>
Written by 0xAX
Related protips
2 Responses

angular-translate has a similar approach :)
In addition, angular-translate doesn't have a jQuery dependency.
Check it out right here: https://github.com/PascalPrecht/angular-translate
Website: http://pascalprecht.github.io/angular-translate/#/guide

@pascalprecht It would be awesome if angular-translate could simply load a en_US.json language file instead of defining it in the config. Is that possible?
Have a fresh tip? Share with Coderwall community!

