Dynamically loading JSON language files in AngularJS

Just starting out with angular and feeling a bit lost...

I want to be able to load different JSON files for data based on the language selected (e.g. json/Agenda-nl.json).

Currently, I have separate controller and HTML files for each language. Is there a way to dynamically load them, possibly using the angular-translate module?

Thanks in advance for any assistance!

var App = angular.module('App', ['pascalprecht.translate']);

App.config(function($translateProvider) {
    $translateProvider.translations('fr', {
        TYPE: 'Type',
        BUTTON_TEXT_FR: 'Français',
        BUTTON_TEXT_NL: 'Nederlands'
    })
        .translations('nl', {
            TYPE: 'Type',
            BUTTON_TEXT_FR: 'Français',
            BUTTON_TEXT_NL: 'Nederlands'
        });
    $translateProvider.preferredLanguage('fr');
});
App.controller('TranslateController', function($translate, $scope) {
    $scope.changeLanguage = function (langKey) {
        $translate.use(langKey);
    };
});

App.controller('AgendaListCtrl', ['$scope', '$http',
    function ($scope, $http) {
        $http.get('json/Agenda-nl.json').success(function(data) {
            $scope.courses = data;
        });
        $http.get('json/language.json').success(function(language) {
            $scope.language = language;
        });
        $http.get('load.php').success(function(loaded) {
            $scope.load = loaded;
        });            

        $scope.selectModel = '1';

        $scope.hover = function(course) {
            // Shows/hides the enroll button on hover
            return course.showOverlay = ! course.showOverlay;
         };

         // create a blank object to hold our form information
        // $scope will allow this to pass between controller and view
        $scope.formData = {}; 

        // process the form
        $scope.processForm = function() {
            console.log("Submitting Form");
            $scope.formData
            $http({
                url     : 'insert.php',
                method  : 'POST',
                data    : $.param($scope.formData),  
                headers : { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }  
            })
            .success(function(data) { 
            console.log(data); 

            if (!data.success) {
                $scope.errormessage = data.errors.message;
                console.log(data.errors.message);
            } else {
                        $scope.message = data.message;
                        console.log(data.message);
                    }
            });
   
        };

    }
]);

Answer №1

Have you considered implementing the loader concept in your project?

I have successfully used a similar setup in the App.config:

$translatePartialLoaderProvider.addPart("agenda");
$translateProvider.useLoader('$translatePartialLoader', {
    urlTemplate: '/app/localization/agenda-{lang}/{part}.json'
})
.preferredLanguage('nl')
.useLocalStorage();
$translateProvider.fallbackLanguage('nl');

The file structure should be organized like this:

app/localization/agenda-nl/agenda.json

app/localization/agenda-fr/agenda.json

The contents of the JSON files could be:

{
    "AGENDA_TEXT": "This is your agenda text"
}

In your application, you can simply reference AGENDA_TEXT and based on the selected language, the text will be translated accordingly.

Does this approach sound feasible to you?

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

Issues with parsing JSON data in Swift's Data structure are causing challenges

I am currently attempting to extract information from the YouTube Data API and convert it into a string using Swift. To achieve this, I am utilizing Alamofire along with SwiftyJSON. However, when attempting to parse the data, SwiftyJSON fails to do so, res ...

"Caution: Please be aware of potential header errors when accessing a static map through AJAX

When attempting to retrieve a static map image using AJAX to check for errors, I encountered the following message: Refused to get unsafe header "x-staticmap-api-warning" (seen in Chrome) I am not very familiar with headers, but it appears that they nee ...

Tips for assigning a single color to each bar in an Angular chart using Chart.js

Here is an example of my HTML code: <canvas id="bar" class="chart chart-bar" chart-data="expenseData" chart-labels="labels" chart-series="series" chart-options="chartOptions" colours= "colours"> </canvas> This is a snippet of ...

The first name of the user is not shown following the completion of the registration

I'm currently developing an application using React and Node.js. In the frontend, I have implemented a functionality where upon logging in, users are redirected from the /login route to the root route and greeted with their first name. However, when a ...

Execute a command via a hyperlink

I have a script that displays information in a div using a button. I am trying to modify it so that it works from a link instead, but I haven't had any success yet. Any ideas on how to make this work? <script> function showCustomer(str) { va ...

Dynamic AJAX Dependent Dropdown Menu

Can you help me create a dynamic input form? I need assistance in creating an input form with a dynamic dropdown list, similar to the screenshot provided below: https://i.stack.imgur.com/rFSqV.png What is my current script setup? The script I have is d ...

Angular 4 is unable to attach to 'formGroup' as it is not recognized as a valid property of 'form'

As a beginner with Angular 4, I decided to explore model driven forms in Angular 4. However, I keep encountering this frustrating error. Template parse errors: Can't bind to 'formGroup' since it isn't a known property of 'form ...

When attempting to send a request for the JSON body to Node.js using the await fetch method, I encountered an issue

Recently, I started working with node js and attempted to fetch JSON data using the code below: const req = await fetch( "http://localhost:3000/api/auth/signin", { method: "POST", header:{ 'Accept':&apo ...

Unable to establish connection with nodejs server from external devices

Currently, I am leveraging a React client along with a Node.js server (MERN Stack). The server operates smoothly on my computer; however, I encounter difficulties when attempting to connect from my mobile phone to the IPv4 of my PC using the correct port ...

How does a JSONP request differ from an AJAX request?

I have searched extensively for a solution to the matter mentioned, yet I did not come across anything intriguing. Would you be able to clarify it in simple terms? ...

Employing the html.validationmessagefor to display a client-side error notification

My text fields have server-side validation messages. The field 'title' is a required field on the server side with a '[Required]' data attribute in the class, but it only seems to be checked on a postback or form submit. I am saving the ...

Generate a randomly structured 2D array called "Array" using JavaScript

Can anyone help me with extracting a random array from a 2D named array? I've tried several solutions but none of them seem to work. var sites = []; sites['apple'] = [ 'green' , 'red' , 'blue' ]; sites['o ...

Is there a way to transform a personalized jquery event listener into an angularjs listener?

A custom event listener was created using jQuery for an angularjs component. The event is triggered by a non-angularjs library. $( "#myDiv" ).on( "CornerstoneImageRendered", function(e) { // buisness logic }); The element myDiv is a div that belongs t ...

Tips for preventing the playback of the sound while recording

When creating a basic JavaScript application that involves opening a stream from the user and analyzing frequencies, I found that while Google Chrome and Opera work well by providing feedback in the headphones, Firefox often remains silent. Additionally, F ...

A guide on coding the source tag script for a payment form in CodeIgniter, specifically for a JavaScript form

Scenario: I have a variable called $data['tabdata'] that I am passing from controller C to view V. This variable includes a script element pointing to http://example.com/1.js. Problem: The script in 1.js is not running properly in the view. This ...

Next and previous buttons on Bootstrap carousel are not functioning properly with certain pop-up modals in a React application

Bootstrap Carousel Implementation for Viewing Photo Groups Utilizing a Bootstrap Carousel, I have created a feature to display different groups of photos. Each group of photos can be clicked on to open a Modal, showcasing all the images in a carousel form ...

GSAP also brings scale transformations to life through its animation capabilities

I have an SVG graphic and I'm looking to make four elements appear in place. I've been using GSAP, but the elements seem to be flying into place rather than scaling up. Here's the code snippet I've been using: gsap.fromTo( ...

Firefox not clearing Highcharts points properly

I am currently utilizing highcharts to generate dynamic charts when hovering over a table row. My goal is to clear and hide the chart once the mouse moves away from the row. While this functionality works smoothly in Chrome, I am encountering a strange is ...

Option list malfunctioning in Safari, Mozilla, as well as Chrome browsers

I encountered some issues while working on the front-end of my web app. Here are a few problems: I need to truncate text if it's too long, so I use the following CSS: .suggestion-box-text { white-space: nowrap; overflow: hidden; text-overfl ...

Interconnected directives, inheriting scope, and monitoring data flow from parent to child

I'm struggling to configure a couple of directives with a parent/child hierarchy and I'm facing some challenges in understanding how scope is managed within nested directives. My goal is for a child directive to react to changes in a parent direc ...