Storing the translated value from angular translate into a global variable: a guideline

I've been grappling with this issue for quite some time now without much success.

My goal: I'm attempting to store the value of an angular translation (using $translate) in a global variable so that I can later use it for assigning dynamic variable values. These translations are stored in a json file and configured within angular.module(..).config(..)

This is what my js file looks like:

angular.module('myApp').controller('MyCtrl',
    function ($translate, $scope) {
        var temp_text='';
        $translate(['Text1']).then(function (translations) {
            temp_text=translations.Text1;
            alert(temp_text);
        });
        alert(temp_text);

});

The issue here is that the temp_text value appears as empty in the first popup, but correct in the second one.

Any ideas on how I can retain the translated value in a global variable for future reference?

Answer №1

Utilizing $rootScope to store a variable or data shared across all controllers in your application is a convenient approach.

Your controller implementation should resemble the following:

angular.module('myApp').controller('MyCtrl',
function ($translate, $scope,$rootScope) {
    var tempValue='';
    $translate(['Text1']).then(function (translations) {
        tempValue=translations.Text1;
        $rootScope.myGlobalVar=tempValue;
    });

});

Here's a live demo link for reference.

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 trigger a function once another one has finished executing?

After opening the modal, I am creating some functions. The RefreshBirths() function requires the motherId and fatherId which are obtained from the getDictionaryMother() and getDictionaryFather() functions (these display my mothers and fathers on the page s ...

Using Angular 2 for two-way binding with input masking

Encountering an issue with ng2 and inputmask. Here is the code snippet that's causing trouble: <div class="form-group col-sm-7"> <label class="control-label" for="sender-phone">Phone *</label> <input type="text" [(ngModel) ...

Tips for formatting the return Date when utilizing the setDate() method

I set the end of the week to be the upcoming weekend using the following code snippet this.weekEnd = new Date(this.currentDate.setDate(end)); Now, my goal is to update the weekEnd by adding 7 days to it. I attempted to achieve this as shown below, however ...

The challenge of populating information within a Datalist

In my code snippet, I have a JavaScript function that is used to populate a Datalist: function PopulateDropDown(facility) { $.ajax({ url: '/Rentals/Base/GetContactsForFacility?selectedFacility=' + facility, data: { facility: ...

Ways to extract JSON data from multiple JSON arrays

Within the snippet below, I am attempting to extract the value of women. Right now, I can successfully retrieve 1. Personal care appliances and 2. Jewelry. However, if I try to check any checkbox after that, I encounter an error stating "Uncaught TypeError ...

The jQuery UI Dialog is experiencing an issue with a button that is triggering a HierarchyRequest

I am facing an issue with a piece of javascript that works perfectly on other pages but is now throwing a HierarchyRequestError on a new page. This leads me to believe that there may be an HTML problem on this particular page. Here is a simplified version ...

Getting an image from a NodeJS backend to a React frontend

I successfully uploaded an image using the multer library in Express, storing it in the path Backend->Uploads/ and saving the image path in MongoDB. My project is structured as DirectoryName Backend Uploads Frontend While I can access the ima ...

The file_get_contents() function encountered an issue as the content type was not specified, leading to it assuming

I am currently working on a project using PHP and JavaScript. I need to call an API from the camera using PHP code. I am using the file_get_contents function and Post request for this purpose. Below is the code snippet: $value = $_POST['TakeNewPic&ap ...

Enhance Image Size with a Custom React Hook

I've created a function to resize user-uploaded images stored in state before sending them to the backend. const [file, setFile] = useState(null) function dataURLtoFile(dataurl, filename) { let arr = dataurl.split(','), mime = arr[0].ma ...

Tips for effectively managing dynamic xpaths

When conducting a search operation, I am required to select the text that is returned as a result. Each search will produce different xpaths. Below are examples of various xpaths returned during a search: .//*[@id='messageBoxForm']/div/div[1]/di ...

Issue with JQuery's parentsUntil method when using an element as a variable not producing the desired results

I'm having trouble with a specific coding issue that can be best illustrated through examples: For example, this code snippet works as expected: $(startContainer).parents().each(function(index, parentNode) { if (parentNode.isSameNode(commonConta ...

Utilizing jQuery in Wordpress to Toggle Content Visibility

Currently, my website pulls the 12 most recent posts from a specific category and displays them as links with the post thumbnail image as the link image. To see an example in action, visit What I am aiming to achieve is to enhance the functionality of my ...

Guide to deploying an AngularJS application on Heroku with Node.js without the use of yeoman

I am currently working on deploying a Hello World build using AngularJS in Heroku with Node.js, incorporating multiple views (partials). Initially, I successfully deployed a basic Hello World without utilizing ngRoute, which means without partials. Howeve ...

Modification of text within a text field via a context menu Chrome Extension

Currently, I am embarking on my first endeavor to create a Chrome extension. My goal is to develop a feature where users can select text within a text field on a website using their mouse and have the ability to modify it by clicking on a context menu. Be ...

Conceal user input field in React using a hook

I am looking for assistance with a form that has 4 input fields: username, password, email, and mobile. My goal is for the email field to disappear if an '@' symbol is typed in the username field, and for the mobile field to disappear if any digi ...

Eliminate the hover effect from every element

Is there a method in CSS or Javascript that allows me to eliminate the hover effect on all elements? I am specifically looking for a solution that will disable the hover effect on mobile devices while keeping it intact on desktop. I attempted using pointer ...

The Ajax function is not defined and results in a runtime error being thrown

customAjax.postJson( "/foo/GetFoo", { fooName: fooName }, function (data) { }, function (error) { }); }; My Rest api call is GetAsync() It throws customAjax is unde ...

Use the AngularJS ng-repeat filter to display items only if their class matches a

I have a specific requirement for two select fields. In the second select field, I want to filter the options based on what is selected in the first one. This filtering needs to be done using class names. Here's an example of how the select boxes are ...

Leverage the power of AJAX for searching in Laravel 5.3

This section contains views code related to form submission: {!! Form::open(['method'=>'GET','url'=>'blog','class'=>'navbar-form navbar-left','role'=>'search']) !! ...

Failure to trigger Summernote's OnImageUpload function

After transitioning to the latest version of Summernote, which is Version 7, I encountered a problem with the image upload functionality. Despite specifying the line onImageUpload: function(files) {sendFile(files[0]);}, it seems that this code is not being ...