Switching between languages dynamically with Angular JS using $translateProvider and JSON files

I currently have a collection consisting of 6 different JSON files.

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

An illustration of the data present in each file is as follows (in this instance, considering en.json):

{
    "SomeText": "Test in English"
}

At present, I am implementing this in my configuration 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 particular example functions seamlessly for my desired outcome, initially loading English and automatically refreshing upon changing languages.

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

However, I am now looking to utilize JSON files for enhanced organization but I believe the current syntax won't suffice.

How can I integrate all 6 files into the configuration and facilitate switching between them with any function similar to the aforementioned example?

Answer №1

Consider treating it as an array, here's an 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 you can access the translation like this:

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

This will return "Test in English"

The structure of the app might vary but this example provides a basic idea.

Check out this javascript example https://jsfiddle.net/uw0pg8jm/

Using this approach makes it easier to switch between languages. Here's an example using jQuery and javascript. The implementation would be different with Angular due to its event binding mechanisms. https://jsfiddle.net/zu6h7nh7/1/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with npm installation leading to missing node_modules directory

When attempting to run npm install . in a local directory, I keep encountering the following errors: npm ERR! install Couldn't read dependencies npm ERR! Darwin 15.2.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "." npm ERR! no ...

Maintaining consistent height using JavaScript

Dealing with equal height using just CSS can be a hassle, especially when you want to support older browsers like IE9. That's why I've decided to use JavaScript instead. If a user disables JavaScript, having unequal heights is the least of my con ...

Comparing obj.hasOwnProperty(key) with directly accessing obj[key]

Consider the scenario where I need to determine if a property exists within an Object. A comparison between two methods caught my attention: if(object.hasOwnProperty(key)) { /* perform this action */ } OR if(object[key]) { /* perform this action */ ...

Compiling this HTML template in dev mode with Vue is agonizingly slow

I've been working with a template app setup that was bootstrapped using vue CLI. Within one of my components, I have 20 nested div tags. During development mode, it's taking roughly 10 seconds to compile this component. The more deeply I nest HTM ...

What is the reason behind not being able to assign identical names to my SailsJS models and MySQL tables?

Recently diving into Sails JS, I found myself in unfamiliar territory with RESTful APIs. Following the guide, I created a User model to correspond with my existing users table. Adding attributes based on the table's columns was straightforward, and a ...

React Native not refreshing state data

I'm working with a FlatList that contains the code snippet below: <FlatList ........... refreshing={this.state.refresh} onRefresh={() => { this.setState({ ...

``There seems to be an issue with the functionality of a basic AngularJS directive

I have created a basic directive with some parameters passed, however the parameters are not being displayed on the template when used in the code. No errors are shown either. I tried using '@' instead of '=', but it didn't make mu ...

When attempting to access the length of a JSON array, it results in undefined

I recently received a JSON encoded array from an AJAX call that looks like this: {"country":{"0":"United States of America","United States of America":{"states":{"0":"Alaska","Alaska":{"cities":["Adak","Akiachak","Akiak","Akutan","Alakanuk"]}}}}} Below ...

Avoiding page refresh while utilizing the ng5-slider component in Angular

I am currently working with an ng5-slider that has a customizable range from 0 to 1000. However, I have encountered an issue when adjusting the slider at the bottom of the page - it refreshes and automatically takes me back to the top of the page. I would ...

Uploading files into an array using Angular 2

Struggling to incorporate an uploader within an array: I've got an array of users displayed in a table using "ng-repeat". I want to add a column with a button to upload an image for each user. Currently, I'm utilizing ng2-file-upload, but open t ...

Harness the power of our custom directive when integrating with x-editable functionality

Is it possible to apply a custom directive to an editable-text element? <span ui-Blur="testfn(price);" editable-text="entry.product_id" e-name="product_id" e-style="width: 200px" e-form="sentryform" e-required> </span> ...

"Encountering an issue where the route function in Passport and ExpressJS is not being

When using passport for admin authentication, I am facing an issue where the redirect is not calling my function. Consequently, all that gets printed on login is [object Object] Here is my code: app.get('/admin', isLoggedIn, Routes.admin); ...

Craft fresh items within HTTP request mapping

I am currently working on a function that subscribes to a search api. Within the map function, my goal is to transform items into objects. I haven't encountered any errors in my code, but the response always turns out empty. Here's the snippet o ...

Mysterious distortion of JSON strings in Tomcat

I am facing an issue with JSON-String distortion when sending it from a JavaFX application to a Tomcat server. Some symbols are being replaced by strange square symbols: https://example.com/image1.png The conversion of JSON to pass correctly - verified b ...

The parameters in VueJS are malfunctioning on this webpage

I created my vue in an external file and included it at the bottom of my webpage, but I am encountering issues with its functionality. One specific problem arises when using v-model, resulting in a template error displayed on the page: Error compiling t ...

What is the best way to locate the position of a different element within ReactJS?

Within my parent element, I have two child elements. The second child has the capability to be dragged into the first child. Upon successful drag and drop into the first child, a callback function will be triggered. What is the best way for me to determi ...

How can I adjust the font size in a TextField when it is in focus?

As a novice in ReactJS, I am currently utilizing materia-ui to design a page. I am looking to make a custom change on a TextField where the font size adjusts when text is entered. However, adjusting the font size creates too much space between the label a ...

Why doesn't jQuery ajax work when sourcing the URL from a variable but works with a hard-coded URL?

During my experimentation with setting and getting the URL for a jQuery Ajax (post) call, I realized the value of dynamically setting the destination URL for the request. Here's how I attempted to achieve this: To set the URL to 'store.php' ...

Text input setting for jQuery UI Slider

Currently, I am utilizing jQuery UI sliders to input values in text boxes. However, I would like this functionality to be bidirectional; meaning if a value is entered into the text box, I want the slider to move to the corresponding position. I am unsure ...

Is there a way to disable automatic spacing in VS code for a React file?

I am currently working on my code in VS Code within my JSX file, but I keep encountering an error. The issue seems to be that the closing tag < /h1> is not being recognized. I have attempted multiple methods to prevent this automatic spacing, but so ...