0

I have a folder with 6 different JSON files.

en.json
es.json
fr.json
it.json
ja.json
zh.json

An example of the content that is inside of each file is like the following (this case is for en.json):

{
    "SomeText": "Test in English"
}

I am currently using this on my config file.

$translateProvider.translations
(
    'en',
    {
        SomeText: 'Test in English'
    }
)
.translations
(
    'zh',
    {
        SomeText: 'Test in Chinese'
    }
)
.translations
(
    'it',
    {
        SomeText: 'Test in Italian'
    }
)
.translations
(
    'fr',
    {
        SomeText: 'Test in French'
    }
)
.translations
(
    'ja',
    {
        SomeText: 'Test in Japanese'
    }
)
.translations
(
    'es',
    {
        SomeText: 'Test in Spanish'
    }
);

This last example works perfectly fine for what I want to accomplish, which is doing an initial load of english, and then if I switch languages, it will automatically refresh it.

var example = 'ja';
$translate.use(example);

However, now I want to use JSON files for a better structure, but I don't think I can use that same syntax.

How can I add all 6 files to the config and have them switched from any function like in the example above?

Victor
  • 1,108
  • 9
  • 29
  • 53
  • Could you give an example of the contents in the JSON-files? You want to load all files and add the contents to $translationProvider.translations? – Arg0n Nov 20 '15 at 15:57
  • I updated the post, showing an example of how the files look like – Victor Nov 20 '15 at 16:06
  • Did you try just fetching the files with $http? $http.get("/location/en.json").then(function(data){ // Add contents }, function(error){ alert(error); }); – Arg0n Nov 20 '15 at 16:19
  • What backend are you using btw? – Arg0n Nov 20 '15 at 16:21
  • Check out this accepted answer: http://stackoverflow.com/questions/13020821/how-to-load-json-into-my-angular-js-ng-model (Load .json with $http in AngularJS). – Arg0n Nov 20 '15 at 17:43

1 Answers1

0

Treat it like an array (example in javascript):

var translations = 
{ 
    "en" : { "SomeText" : "Test in English" },
    "zh" : { "SomeText" : "Test in Chinese" },
    "it" : { "SomeText" : "Test in Italian" },
    "fr" : { "SomeText" : "Test in French" },
    "ja" : { "SomeText" : "Test in Japanese" },
    "es" : { "SomeText" : "Test in Spanish" }
});

then it would be something like:

var language = "en";
var translations[language].SomeText;

This would give "Test in English"

I'm not 100% sure of the structure of the app but I think it gives you the basic concept.

javascript example https://jsfiddle.net/uw0pg8jm/

This way it would be easy to change between languages, say you have two phrases, this is an example in jQuery and javascript. Using Angualar you would bind the events and values differently. https://jsfiddle.net/zu6h7nh7/1/

Dhunt
  • 1,584
  • 9
  • 22