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

Node - Creating personalized error handling functions

Currently in the process of developing custom helper methods to eliminate redundancies, utilizing express-promise-router app.js has set up the error handler middleware //errorHandler app.use((err, req, res, next) => { //const error = a ...

Having trouble reading the JSON file containing the trademark symbol

After receiving some generated json files, I noticed that some of them contain the ™ symbol. Strangely, when attempting to use json_decode on these files, the result is NULL. However, if I manually remove the symbol, the data becomes visible. Below is th ...

Utilizing a setTimeout function within a nested function in JavaScript

Recently delving into the world of JavaScript, I encountered an issue with a code snippet that goes like this: function job1() { var subText1 = ""; var subText2 = ""; var text = ""; var vocabulary = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijkl ...

problem involving php and Json

I am really struggling to understand why I am unable to make this JSON work properly. Here is the response I receive from the API: "{"errorCode":5,"errorDescription":"Unknown account"}" I have attempted various methods in order to retrieve the "Unknown ...

Obtain the height and width of the original images from the href and assign them to your attributes using jQuery

Hey there pals, I'm currently on a mission to fetch the dimensions (height and width) of an image from a hyperlink and then insert those values into its attribute. This task has got me going bonkers! Here's my snippet: <figure> <a ...

Problems encountered with React Image Magnifiers while attempting to zoom in with Next.js

When I try to use the react-image-magnifiers plugin to make an image zoom in on hover, it works fine without next.js. However, when I integrate it with next.js, the zoom functionality does not work. Could there be an issue in my next.config.js file? This ...

Sending data from a PHP array to a JavaScript array within a PHP function

I have been scouring Stack Overflow for a solution to my problem, but I haven't found one that fits my specific issue. I recently took over a project from a former coworker that involves managing all the videos and images for my company. My current di ...

Communication between nodes using serial ports in Node.js fails to receive a response from the connected Arduino board

I've been attempting to establish communication between a computer and an Arduino board using node.js. Despite having a simple program, it just doesn't seem to work as expected. The Arduino program (which seems to be working fine) is as follows: ...

What is the best way to eliminate existing double quotation marks within string values stored in objects in Angular?

When using Angular, data is retrieved in object form from the database to the backend and then to the frontend. Here's how it looks in HTML: <h3>Payslip for the month of {{dataout[0].MonthYear | json }}</h3> The issue arises when running ...

Can you explain the varying methods of importing material-ui components and how they differ from each other?

After delving into the documentation for material-ui and exploring various online resources, it appears that there are multiple methods for importing the same component: import TextField from 'material-ui/TextField'; // or import TextField from ...

Retrieving information from deeply nested dictionaries in Python

Despite finding similar posts, none of the solutions have worked for my specific scenario. I am dealing with a complex dictionary that includes lists and nested dictionaries: data = {'key1': 'value1', 'key2': 'value2&a ...

The proper way to define an event delegator's syntax

Typically, when you want to handle a button click event, you would do so like this: $(document).ready(function() { $("button").click(function() { doSomething(); }); }); However, in the scenario of an event delegator, you may need to respon ...

Adding JavaScript in the code behind page of an ASP.NET application using C#

Currently, my challenge involves inserting a javascript code into the code behind page of an asp.net application using c#. While browsing through various resources, I stumbled upon some solutions provided by this website. Despite implementing them as inst ...

Loading values from an API in an AngularJS module configuration block

I'm working on an app that includes a Facebook login button using the 'angular-facebook' module. In my .config block, I have this code: FacebookProvider.init('myAppId'); However, I need to load the myAppId from a database using a ...

React is unable to identify the `activeStyle` property on a DOM element

Is there anyone who can help with this error message? The warning states: React does not recognize the activeStyle prop on a DOM element. If you want it to be a custom attribute in the DOM, use activestyle in lowercase instead. If it was accidentally pas ...

How can a package be installed through composer? Where is the installation location?

Having recently delved into the world of PHP and Composer after a 20-year hiatus from Linux, I am currently working on a website hosted on Hostinger. My goal is to integrate a package from Cardinity that facilitates VISA payments into my hand-coded HTML/PH ...

Are there any JavaScript charting tools that can draw in a clockwise direction with multiple data points?

Can anyone recommend a JavaScript live chart/graph library that can create clockwise graphs with multiple points, similar to the example below? https://i.sstatic.net/dQfK4.png ...

Why is the image cut in half on mobile devices but displaying correctly on computer screens? Could it be an issue with

There seems to be an issue on mobile screens that does not occur on computer screens. When the user clicks on the image, it disappears, and when they click another button, it reappears. However, there is a problem with how the image appears - it is cut off ...

When trying to validate an HTML form using AJAX, jQuery, and JavaScript, the validation may not

Here is a high-level overview of what happens: The following code functions correctly... <div id='showme'></div> <div id='theform'> <form ...> <input required ... <input required ... <inpu ...

Convert the canvas to an image by right-clicking

Is it possible to treat the canvas element as an image when using drawImage() to draw on it? When I attempt to right click on the canvas element that has been drawn on, the option "Save image as" does not appear. The right click menu displays: What step ...