Modifying the $locale setting in ui-router

My Goal and Approach

Within our AngularJS application, we utilize angular-ui-bootstrap for datepickers. Our aim is to localize the datepickers based on the user's locale. However, dynamically changing the locale in AngularJS poses a challenge due to the lack of an API for such functionality. The user's locale information is retrieved from the backend, prompting the need to adjust Angular's locale before rendering the main state. To address this issue, I propose invoking a service that will inject the appropriate locale file into our application.

The Implementation

The injectorService:

;(function(module) {
'use strict';

function injector($q) {
    var body = document.getElementsByTagName('body')[0];
    return {
        addScript: function(url, async, cb) {
          return $q(function(resolve, reject) {
              var script = document.createElement('script');
              var loaded;
              script.type = 'text/javascript';
              script.setAttribute('src', url);
              script.onreadystatechange = script.onload = function() {
                if (!loaded) {
                  if(cb && _.isFunction(cb)){
                      cb(null, 'ok');
                  } else {
                      return resolve('ok');
                  }
                }
                loaded = true;
                resolve('loaded');
              };
              script.onerror = function(error) {
                  if(!error.isTrusted){
                      if(cb && _.isFunction(cb)){
                          cb(error, null);
                      } else {
                          reject(error);
                      }
                  } 
              };
              body.appendChild(script);
          });
      }
    };
}

module.factory('Injector', injector);

}(angular.module('injector', [])));

In initializing the main state, the following code is called within the resolve section

            resolve: {
                    env : function(userService, Injector) {
                        return userService.getLocale()
                            .then(function(env) {
                                var userEnv = env;
                                var baseUrl = '/app/';
                                var angularSpecificLocale = '';

                                switch(userEnv.userlocale){
                                    case 'fr':  
                                  angularSpecificLocale = baseUrl + 'fr.js';
                                    break;
                                case 'ro':
                                  angularSpecificLocale = baseUrl + 'ro.js';
                                    break;
                                default:
                                  angularSpecificLocale = 'en';
                                  break;
                                }
                                // Omit any locale files if set to English by default
                                if(angularSpecificLocale === 'en'){
                                    return userEnv;
                                } else {
                                  return Injector.addScript(angularSpecificLocale)
                                    .then(function() {
                                        return userEnv;
                                    });
                                }
                            });
                    }
                }

The Challenge

Despite my efforts, the datepicker remains unlocalized. It seems like there may be a missing step in the process. By adding the following snippet in my code:

angular.injector(['ngLocale']).get('$locale')

I can confirm that the locale id is correct. Any assistance without relying on external libraries would be greatly appreciated!

Thank you :)

Answer №1

To achieve this, I am utilizing the angularDeferredBootstrap module:

deferredBootstrapper.bootstrap({
    element: document.body,
    module: 'frontApp',
    resolve: {
        userLang: ['$http', function ($http) {
            return $http.get('/api/userLanguage');
        }]
    }
});

Subsequently, you have the ability to inject and utilize userLang throughout your application.

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 most effective method for informing the browser about changes in the database?

I've been working with django for about 6 months now and it has been effective for the websites I create. However, I recently encountered an issue while developing a website where users receive notifications whenever another user updates a blog post. ...

Unleashing the power of JavaScript: Sharing arrays and data structures effortlessly

Currently, I am utilizing HTML & JavaScript on the client side and NodeJs for the server side of my project. Incorporated in my form are multiple radio buttons. When the user clicks on the submit button, my intention is to post the results to the server. ...

Leverage the generic types of an extended interface to simplify the creation of a shorthand type

Attempting to streamline my action shorthand that interacts with AsyncActionCreators. A function has been crafted to accept a React dispatch: Dispatch<T> parameter: const fetchProfileAction = actionCreator.async<void, Profile, any>('FETC ...

Tips for saving and retrieving req.user using JsonwebToken

Looking for ways to store and retrieve req.user using JsonwebToken in my booking application built with Node. I need to fetch the user information who booked a product and display it on the admin portal. .then((user) => { const maxAge = 3 * 60 * ...

Conceal varying numbers of rows in a table using Jquery based on specific

I am attempting to hide certain table rows, but I am encountering an issue. Currently, when I click on a row with the class 'plevel1', it hides the following row with the class 'plevel2'. However, when I click on the top parent level ro ...

Guide on transferring JavaScript Objects from the Front End to Spring Boot Back-end and effectively processing and parsing them

After struggling with this issue repeatedly while developing my web apps, I've reached a breaking point and need some help. My frustration might come across as venting, but I'm genuinely stuck. The challenge I'm facing is sending key-value ...

How can you make a Tempory Drawer wider in Material Components Web?

Increasing the Width of a Temporary Drawer in Material-components-web Greetings! I am currently facing an issue with Material-components-web In the provided demo here, I would like to extend the width of the Temporary drawer to accommodate additional co ...

How to dynamically insert li elements into a ul list using the .after() method

After trying to add an li element to the ul list, I noticed that my DOM wasn't updating when checking the page source. Even attempting to delete elements with the delete button didn't seem to work as expected. Here is the code snippet below. ...

html input type called array named AmountMap[1] is unable to be configured with <input type="textbox" size="15" name="amountMap[1]" value="0" >

**Having trouble setting the value of an HTML input type named like an array AmountMap[1] <input type="textbox" size="15" name="amountMap[1]" value="0" > When trying to set amountMap[1].value='10', ...

initial cookie value not established in angular js

I need help passing a cookie value from one UI to another page. The specific cookie value I want to retrieve is the user's username, for example: Nithya When I log in to the home page, the cookie value appears empty until I refresh the page. Is the ...

The alert box for model validation summary errors is deactivated when hidden using .hide() method

In my MVC web application form, there is an optional postcode finder. If there is no match for the entered postcode, I add a custom error message to the .validation-summary-errors section. After the error is fixed, I remove all instances of the postcode cl ...

Why is there a CSS reference failure in Express and how can it be resolved?

Below, you'll find a simple express server I've put together: // check out my basic Express server var express = require("express"); var app = express(); var bodyparser = require("body-parser"); app.use("/public/", express.static("./public/")); ...

Encountered an issue following deployment to Heroku (Application error)

Introduction I recently created a Login form for my project. The frontend is deployed on Netlify at this link, and the backend is hosted on Heroku which can be accessed here. To view the backend logs, click here Here is a snippet of my index.js file: co ...

The drop-down menu does not maintain its selected option after the window is refreshed

I am struggling with a dropdown list as shown below: <select class="span2" id ="sort" name= "order_by"> <option >Default</option> <option >Price</option> <option >Color</option> ...

When using NodeJS, having multiple 'if' statements may result in conflicting headers being returned,

Introduction to Promises. Encountering challenges in NodeJS due to the utilization of multiple if-statements and return-statements. Considering leveraging Promise as a potential solution. This snippet showcases an example: const express = require(' ...

How to fetch files using URL in JavaScript

I need a solution for automatically downloading multiple PDF files from Google Drive and Docs using their URLs with JavaScript code. I don't want to manually go to each link to download the files. Although I've researched various answers on Stac ...

Tracking and managing user clicks on external links within a vue.js application

I am currently working on a web application that retrieves data from a CMS. Utilizing the Vue-Router in 'history' mode, I need to address content fetched from the API which may include links. My goal is to manage specific links using the router w ...

Passing Laravel environmental information to a Vue component

I am struggling to retrieve my Stripe keys from my Laravel .env file and pass them into my Vue component. I came across some similar inquiries on Stack Overflow and the Laravel documentation that suggest using the MIX prefix, allowing me to access process. ...

when the submit button is clicked, verify whether the input field is empty

I have exhausted all my options and nothing seems to work. All I want is for the following functionality to be implemented: When a submit button is clicked -> check if a text field is empty -> if it is, display an error alert and prevent advancing t ...

Using the ng-change directive in an ng-repeat loop within AngularJS allows

Is there a way to cancel out the response in the answer field using an ng-change event on the dropdown box? I need a method to dynamically access the answer field. The code is within ng-repeat tags. For more information, please visit this PLUNKER. ...