A translation module for AngularJS
You can install with bower or npm
Include dist/angular-translator.min.js in our index.html, after including Angular itself.
Inject ngTranslator to your main module's list of dependencies.
In app.run method configure the translation module (This is the best way but you can do this wherever you want):
app.run(
function($translator){
$translator
.configure({
language : "en", //name of en.json
path : "languages/", //root directory for languages
default : "en" //default language
});
});
Angular-translator working with external file for translations.
Create a folder in your project, for example ./languages, and put inside your translations file in json format.
For example you can create two languages (en.json and it.json) for English and Italian and sould be something like:
{ "say_hi": "Hello World!" }
{ "say_hi":"Ciao Mondo!"}
In the example below i use always <span> element but you can use whatever you want
Used for a simple text to translate
{ "title" : "Hello World!" }
Used for translate a string that contain runtime data.
You can define your dynamic content with
@param_name then use
translated-params in your HTML tag for passing @param_name value.
Check the sample below:
$scope.version = {"version":"v0.0.1"};
{"description": "A translation module for AngularJS. [@version]"}
Used for translate placeholder in input filed. Insert in you translated tag placeholder-translated
{
"form": {
"username": {
"label": "Username",
"placehoder": "Insert your username"
},
"submit": "Submit",
"cancel": "Cancel"
}
}
Used for translate a string that can be single or prural. In the example below there is a combination of parameters and prural. In your <lang>.json file you should define an array with two elements and in position 0 the sentece for the single case and in position 1 the sentence for the prural case.
$scope.results_value = {
"one": {
"value" : 1
}
};
{ "results": ["@value result", "@value results"] }
This chapter is for understand better how to define you json file for a language.
{
"home_page": {
"title" : "Home page",
"results": [
"@value home page result",
"@value home page results"
],
"form_inputs": [
{
"label": "first label input",
"placeholder": "first input placeholder"
}
]
}
}
Inject $translator service in your controller/service/etc.. for a run time translation with $translator.translate(<key>, <params>, <prural_value>)
app.controller('..', ['$scope', '$translator',
function($scope, $translator){
$scope.translation = function(){
alert(
$translator.translate('message_in_controller', {param_1: "parameter"}, 1)
);
}
}
);
{ "message_in_controller": "Dynamic translation!" }
Messaggio italiano!
English Message!
$scope.switch = function _switch(lng){
// async method. When finish call $compile.
$translator
.changeLanguage({
language : lng,
path : "languages/",
default : "en"
});
}
{ "message" : "English message!" }