Storing multilingual JSON data in AngularJS for faster access

I have successfully implemented a multi-language concept in my application, but I am facing an issue where the language (.json) file is being loaded for every field. As a result, the application takes a longer time to load. My requirement is to load the .json file only once to fetch all the data. How can I achieve this in AngularJS? Thank you in advance for your assistance.

Feel free to check out the link below as well:

http://plnkr.co/edit/PYZxcI5yTNuA0fEern9s?p=preview

var language = 'en';

app.directive('telBasictext', ['$http', 'teli18nservice',
  function($http, teli18nservice) {
    return {
      restrict: 'AEC',
      require: 'ngModel',
      scope: {
        ngModel: '=',
      },
      template: '<div  class="form-group"  > ' +
        '<label  >  {{ setvalue }} </label> ' +
        '<div  > <input type="{{ textboxtype }}" ng-model="ngModel"  ></div></div>',

      link: function(scope, iElement, iAttrs, ngModelController) {
        var collecton = iAttrs.getString;
        var splitValues = collecton.split(",");
        var language = splitValues[0]; // Language EN or Fr
        var labelName = splitValues[1]; // Label Name
        var moduleName = splitValues[2]; // Module Name (global or local)
        teli18nservice.getdata(moduleName).success(function(data) {
            scope.setvalue = data[labelName];
          })
          .error(function(error) {
            scope.setvalue = "No Label";
          });
      }
    };
  }
]);

Answer №1

To store the outcome of a JSON request locally in your teli18nservice service and then use that data for future calls to getdata, you can implement the following code snippet:

// teli18nservice
var jsonData;
this.getData = function () {
    if (jsonData) {
        return $q.resolve(jsonData);
    }
    $http.get().then(function (res) {
        jsonData = res.data;
        return jsonData;
    });
}

You may also want to explore the concept of caching $http responses.

Answer №2

Have you thought about utilizing the $http cache?

Here's an example referenced from this source:

var cache = $cacheFactory('myCache');
var data = cache.get(someKey);

if (!data) {
    $http.get(url).success(function(result) {
        data = result;
        cache.put(someKey, data);
    });
}

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

What is the best way to populate a table view with an array of data when the Next button is tapped in iOS using Swift

Currently, I am attempting to load detailed array items into a table view. The table view consists of an array of labels and two buttons placed on the navigation bar labeled Next and Previous. When the user taps on the Next button, it will replace the arr ...

What methods can be used to send JSON data in the body of an express router.get request?

I am currently working on setting up an express endpoint to fetch data from an API and return the JSON response in the body. We are receiving JSON data from a rest API as an array and my goal is to utilize express router.get to present this formatted JSON ...

Error message: The call stack size has surpassed the limit, resulting in a RangeError. This issue is

I currently have a dynamic unordered list within my HTML file. Upon loading the page, certain list items are automatically added. The original format of the list is displayed as follows: <ul class="ui-front"> <li><div>1</div& ...

Is it possible to modify the colors within a JavaScript string?

I am currently working on creating a multi-timezone clock that will be shown in a web browser in kiosk mode. The basic code was taken from and the kiosk setup from: and then customized into: However, I am struggling to change the color of each timezon ...

Analyze items in two arrays using JavaScript and add any items that are missing

I am working on a JSON function that involves comparing objects in two different arrays, array1 and array2. The goal is to identify any missing items and either append them to array2 or create a new array called newArray1. Here is an example: const arra ...

What is the process for using dojo to load content?

As I work on creating a single-page website with the help of dojo, I refer to tutorials that explain how to utilize dojo/request for ajax requests. The process is straightforward - simply make a request, receive HTML content, and insert it into a designate ...

Using PHP to organize JSON

Could anyone assist me with formatting my JSON data correctly? I need to create parent objects for each activity and then add children to them. For example, 'Test' should have one parent activity with two children, and 'Test2' should ha ...

I am encountering an error with an Unhandled Promise Rejection, but I am unable to determine the reason behind it

const express = require('express'); const cors = require('cors'); const massive = require('massive'); const bodyParser = require('body-parser'); const config = require('../config'); const app = express(); ...

Can you eliminate the commas and turn it into a string?

function EncryptMessage(message) { var encryptedArr = []; for(i=0;i<message.length+1;i++){ var unicode = message.charCodeAt(i); var encryptedUnicode; var newCharacter = String.fromCharCode(encryptedUnicode); if( ...

Looking for a JSON deserializer to work with a third-party case class

I am currently setting up a SecureSocial service in my Scala Play! application, utilizing the ReactiveMongoPlugin to interact with the MongoDB database. Below is the code snippet that I am using: lazy val users: JSONCollection = ReactiveMongoPlugin.db.co ...

Experiencing Error: "Oops! encountering [$injector:unpr] error in angularjs despite correctly including my dependencies."

Here is a glimpse of my factory settings: app.factory('AuthenticationService',['$http', function ($http, $localStorage) { var AuthenticationService = {}; var api = 'http://del1-vm-kohls:8080/Survey' ; Authe ...

Tips for saving/downloading generated QR codes in React Native

Using this code allows me to generate QR Codes, but I am struggling with saving the generated QR Code in PNG or JPEG format. I have tried a few examples without success and I am continuing to try different methods. import React, { Component } from 'r ...

@mui/x-date-pickers styling for the DatePicker component

Despite numerous attempts, I have been unsuccessful in styling the @mui/x-date-pickers <DatePicker/> component. I've experimented with various methods such as sx={{}}, style={{}}, makeStyles(), .css with the !important rule, renderInput={(param ...

Placing a div over a JavaScript element

Is it feasible to overlay a div(1) with a background image on top of another div(2) that contains JavaScript (like Google maps API v3)? I have experimented with z-index without success, and I am unable to utilize absolute positioning because I depend on t ...

Guide to Setting Up Bootstrap 4 Beta Using Bower

Trying to update to the newest Bootstrap 4 Beta version via bower. Issue with this command: bower install bootstrap#v4.0.0-beta Getting the error message: no matches found: bootstrap#v4.0.0-beta Is there something incorrect in my process? This is how ...

Modifying button attribute through dropdown selection

In my project, I have a dropdown that gets its data from a database. Depending on the selection made in the dropdown, I would like to change the attribute of a button (data-uk-modal="{target:'#modal-'value of dropdown'}"). <select id "ci ...

Implementing CSS counter-increment with jQuery

Is there a way to use jQuery to set the CSS counter-increment attribute on ".demo:before" even though jQuery cannot access pseudo elements directly? I recall seeing a suggestion on Stack Overflow about using a data attribute and then referencing that value ...

What advantages does incorporating a prefix or suffix to a key provide in React development?

Is there any advantage to adding a prefix or suffix to the key when using an index as a key in React (in cases where no other value such as an id is present)? Here's an example: const CustomComponent = () => { const uniqueId = generateUniqueId( ...

Issue with error handling in Node and MongoDB when using Express, Mongoose, and the 'mongoose-unique-validator' plugin

I am facing an issue with the 'mongoose-unique-validator' plugin when trying to handle Mongo ValidationError in my custom error handler. Despite other errors being handled correctly, this specific one is not triggering the desired response from m ...

Is it possible to install a Chrome extension specifically for YouTube on Google Chrome?

Hey, I'm trying to eliminate thumbnail images from YouTube. The code I am currently using is: while (true) { $("ytd-thumbnail").remove() } As of now, when I input this code in the console, it successfully removes all thumbnail images. However, I ...