Struggling to modify a variable within an Angular service using AJAX response data and then implementing it for filtering purposes

I've been implementing the code mentioned in this blog post about internationalization with AngularJS, but I'm encountering an issue. ... I want to fetch the "tables" variable from an AJAX request response using "$http get", but for some reason it's not working as expected. Here is the snippet of the code:

var xlat = angular.module('xlat', []);

xlat.factory('xlatService', function ($http) {
    var currentLanguage = 'en';
    // var tables = $.extend(true, {}, initialXlatTables);
    var tables = {
        'en': {
            'textKeys.events': 'Events'
        }
    };

    var service = {
        getData: function () {
            var req = {
                method: 'GET',
                url: 'local/en_US.php',
                cache: true,
                headers: {
                    'Content-Type': 'json'
                }
            };

            $http(req).success(function (data) {
                tables = data;
            });
        },
        setCurrentLanguage: function (newCurrentLanguage) {
            currentLanguage = newCurrentLanguage;
        },
        getCurrentLanguage: function () {
            return currentLanguage;
        },
        xlat: function (label, parameters) {
            service.getData();     
            if (parameters === null || $.isEmptyObject(parameters)) {
                return tables[currentLanguage][label];
            } else {
                return $interpolate(tables[currentLanguage][label])(parameters);
            }
        }
    };

    return service;
});

Despite my efforts, the "tables" variable remains unchanged when using the filter...

var xlat = angular.module('xlat', []);    
xlat.filter('xlat', ['xlatService', function (xlatService) {         
            return function (label, parameters) {
                return xlatService.xlat(label, parameters);
            };
        }]);

Answer №1

Give this a try:

var translate = angular.module('translate', []);    
translate.filter('xlat', ['translationService', function (translationService) {         
    function myTranslator(label, parameters) {
        return translationService.translate(label, parameters);
    };
    myTranslator.$stateful = true;
    return myTranslator;
}]);

For more information on stateful filters, check out - https://code.angularjs.org/1.3.9/docs/guide/filter

Also, remember to load tables in the factory method rather than within the xlat function.

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

The functionality of jQuery date picker and time picker is compromised when the fields are generated dynamically

I am currently utilizing the jQuery code below to dynamically create multiple input fields, which include time pickers and date pickers. However, I am encountering an issue where they are not functioning as expected. $('#add_another_event').clic ...

Attempting to use 'user' before it has been initialized is not allowed

I'm encountering a "Cannot access 'user' before initialization" error in my Mern development controller file for a signup function. Controller/user.js const user = require('../models/user') exports.signup = (req,res)=>{ cons ...

NgZone is no longer functioning properly

Seemingly out of the blue, my NgZone functionality has ceased to work. I'm currently in the process of developing an application using Ionic, Angular, and Firebase. An error is being thrown: Unhandled Promise rejection: Missing Command Error ; Zon ...

Having trouble locating the view in AngularJS, have exhausted all my solutions

After utilizing the ng.Net template in visual studio, I successfully set up my project by adding a new ProgramController.cs, Program.cshtml template, programCtrl.js angular controller, and a program angular module. Despite my efforts, the project just won ...

Transmitting the Flag between PHP and JavaScript

I need help with setting a flag in PHP and accessing it in JavaScript. Currently, I have the following code: PHP if ($totalResults > MAX_RESULT_ALL_PAGES) { $queryUrl = AMAZON_SEARCH_URL . $searchMonthUrlParam . ...

There seems to be an issue with JSX rendering correctly in the code

My JSX code is not rendering properly on my React webpage, and instead of the expected output, I am seeing: <div class='card'>NaNSasha<img src= NaN />Boddy Cane</div>. Here is the component's code: import React, { Componen ...

Symphony 5 and Encore: Issue with Bootstrap JS Loading

Encountering issues while trying to integrate Bootstrap's js with Symfony 5, encore, stimulus, etc... All required dependencies like jquery, popper, corejs are installed and functioning, except for Bootstrap's JS components. The compilation of ...

Placing a div on top of a link renders the link unusable

I am facing a situation and require assistance (related to HTML/CSS/JS) I currently have a div containing an image (occupying the entire div space) such that when hovered over, another div with an image is displayed on top (the second div is semi-transpar ...

Leveraging ruby/watir/page_object for testing a jQuery UI autocomplete feature (AJAX)

Currently, I am utilizing a combination of jRuby, watir-webdriver, and Page Object for conducting tests on a web application. Within the application, there exists a jquery autocomplete widget that yields responses from the backend database following an un ...

The deployment of the Firebase function encountered an issue

For some reason, the Node.js command prompt seems to be ignoring this particular function despite other functions being deployed without any errors. var database = admin.database(); var postsRef = database.ref("/posts"); postsRef.on('child_added&apo ...

Is there a way to send PHP form data without being redirected to the action file? (Utilizing AJAX for data interaction)

When I click a button with $("#btn").load("form.php") in index.php, a form is loaded. I am looking for a way to prevent the page from redirecting to the action file after submission and instead add an item to the table located below the form. You can chec ...

Instructions on displaying a pop-up message upon clicking the edit button with the use of javascript

How can I display a popup message box when the edit button is clicked on my PHP page? I want to confirm before passing data to the edit page, but currently, the data is being sent without displaying any message. Any suggestions on how to fix this issue w ...

Is there a way to implement multiple "read more" and "read less" buttons on a single page?

I am currently working on a rather large project and I am encountering some issues with the read more buttons. As someone who is fairly new to JavaScript, I am still grappling with the concepts. While I have managed to make the function work for the first ...

How can I retrieve the content from an iframe whenever its state is altered using jQuery?

I am currently working on a project where I need to extract the content from a hidden iframe and display it as HTML in a div every time the iframe changes its loading state. The goal is for it to appear as if the page is being redirected and downloading it ...

Angular - why ng-keydown is not correctly enforcing validation?

Take a look at this jsFiddle (Please note that the ng-keydown function isn't triggering, but that is not the main issue in the example) I'm attempting to implement validation for an input box so that only numbers from 0 to 100 are allowed using ...

Learn how to collapse a list by clicking outside of it on the document with the following code: $(document).on("click"

I want to create a collapsible/expandable menu for my website. I had a version where hovering over a category would expand the subcategory, but what I really need is for the subcategories to expand when I click on a category and remain expanded until I cli ...

Combining Mocha, BlanketJS, and RequireJS has resulted in the error message "No method 'reporter'."

While using Mocha with RequireJS, my tests are running smoothly. However, I encountered an issue when trying to incorporate blanket code coverage. The error Uncaught TypeError: Object #<HTMLDivElement> has no method 'reporter' keeps popping ...

Automatically install npm packages after the decision by npm to discontinue programmatic API access

Until npm 8.0, developers had the ability to programmatically install npm packages using this code snippet: const npm = require('npm'); npm.load((error) => { if (error) return console.log(error); npm.commands.install([package], (error, ...

Babel continues to encounter issues with async/await syntax, even with all the necessary presets and plugins installed

I am encountering a compiler error while attempting to compile an async/await function using Babel. Below is the function in question: async function login(username, password) { try { const response = await request .post("/api/login") . ...

An advanced password checker that notifies the user of any spaces in their password

I need help fixing my JavaScript code. The program should prompt the user for a password using a dialogue box, and then validate that the input has no spaces. If a space is detected, the program should stop and display an alert saying "Invalid, contains a ...