The error message that occurs when using angularjs $scope.$apply() is: Error: [$rootScope:inprog]

Having trouble updating text on a page within the $scope. Facing this error message:

Error: [$rootScope:inprog] [http://errors.angularjs.org/1.2.15/$rootScope/inprog?p0=%24apply]
at Error (native)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:6:450
at m (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:101:443)
at h.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js:108:301)
at h.$scope.changeLang (http://treenovum.es/xlsmedical/js/medical-app.js:80:16)
...

Clearly, I'm missing something. :) Any suggestions on how to resolve this? Need the page to reflect the updated variables in the scope.

Here's the code snippet for the update process:

medicalApp.controller('MainCtrl', function($scope, $cookies, getTranslation) {
    getTranslation.get(function(data){
        $scope.translation = data;
    });

    $scope.changeLang = function (lang) {
        console.log(lang);
        $cookies.lang = lang;
        $scope.$apply(function(){
            getTranslation.get(function(data){
                $scope.translation = data;
                console.log(JSON.stringify($scope.translation));
            });
        });
    };
});

The HTML portion:

<body ng-controller="MainCtrl">
    ...
            <div class="header-lang col-xs-4">
                <p>
                    <a href="#" ng-click="changeLang('de')">DE</a> | 
                    <a href="#" ng-click="changeLang('fr')">FR</a></p>
            <div>{{ translation.text }}</div>  <---- Example variable I want updated.
    ...

Also using ngRoute with separate controllers for different pages loaded, could that be causing the issue?

Answer №1

In case your template remains unchanged after modifying models and you require the use of $scope.$apply, consider utilizing $scope.$applyAsync as an alternative.

Link to related discussion on GitHub

Answer №2

By incorporating $scope.$apply(...) within the function changeLang, you may encounter the common error of 'already in a digest'. It is unnecessary to place the getTranslation call within a $scope.$apply(...) block because ng-click already handles this for you. Remove that section and it should function correctly. Additionally, I suggest utilizing a non-minified version of angular during development to better identify errors in the console.

Answer №3

The $evalAsync function in AngularJS is incredibly useful:

$scope.$evalAsync(function() {
    // Your code goes here
});

Alternatively, you can use it like this:

$scope.$evalAsync();

For more information, check out: https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$evalAsync

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

An Unexpected Token Leads to a SyntaxError in Jest's CSS-Modules

I have successfully configured my jest to allow the usage of static files by following their detailed documentation. However, despite implementing the instructions correctly, I am still encountering an error: What steps can I take to resolve this issue an ...

Generate new variables based on the data received from an ajax call

Suppose there is a .txt file containing some integers separated by spaces, like '22 1 3 49'. I would like to use Ajax to read the file as an array or list, and then save each integer as a JavaScript variable. Currently, this code reads all cont ...

Navigating through a URL to grab a specific JSON object: a step-by-step guide

When I receive a json from a URL containing numerous objects, how can I extract only the slugs provided in the json below? I am open to solutions using either PHP or JavaScript. On one hand, I need to understand how to specifically retrieve the desired ob ...

Change a camelCase string to ALL_CAPS while adding underscores in JavaScript

Currently, I'm dealing with a situation where I have a list of variables stored in a file that I need to convert into all capital letters and separate them with underscores using JavaScript. The variable pattern looks something like this: AwsKey Aw ...

Implementing Isotope layout in Reactjs with data-attributes for filtering and sorting content

I am currently working on optimizing the isotope handler within a react component. My goal is to implement filter options such as category[metal] or category[transition], as well as combo filters like category[metal, transition]. Here is the sandbox for t ...

Node.js Project Using a Specific URL and Parameter

Two things are on my mind: 1. I'm trying to set up my project's URL as 127.0.0.1:8080/param=id, but I've been unsuccessful so far despite attempting the following: app.get('/param=id', function(req, res) { console.log(req.param ...

Error message: jQuery expression not being detected

Here is some html code that I have in my view: <div id="divLoginName" style="display: none"> <input type="hidden" id="hidLoginName" /> @Html.TextBox("txtEditLoginName", null, new { maxlength = "1000", tabindex = "0", Multiline ...

I have noticed that the Javascript code is being loaded prior to the completion of my HTML/CSS page for some unknown

I am completely new to the world of web development. I'm encountering an issue where my JavaScript code (specifically alerts) is loading before my HTML/CSS page has fully loaded. I've been using sample alerts to test this out, and ideally, they s ...

When using the Ng --version command on a development package, it throws an error

I encounter an error with a development package when cloning a repository. I would greatly appreciate any advice on how to resolve this issue. https://i.stack.imgur.com/DBp5r.png ...

Error in NodeJs: ReferenceError - the variable I created is not defined

Encountering an issue while attempting to use a module in my router file. I have successfully required it, but now I am seeing the following error message: ReferenceError: USERS is not defined at c:\work\nodejs\router\main.js:32 ...

Show the complete JSON data on the webpage

I'm trying to remember how to display all the data within an ng-repeat using $index, but it's not coming back to me. Usually, when I've done this in the past, it just displays everything in the HTML of the page like: array: [ { animal: "dog ...

Utilizing jQuery/Javascript to replicate the data from a table while excluding the header and then pasting it to the

I am attempting to replicate the data from a table while disregarding the header/title row and copying it to the clipboard in the exact same way as manual selection and copy. I came across a post on how to choose Select a complete table with Javascript (t ...

Employing v-btn for navigating to a different route depending on whether a specific condition is satisfied

Is there a way to prevent this button from redirecting to the specified URL? I want to implement a validation check in my method, and if it fails, I need to stop this button from performing any action. Any suggestions or assistance would be highly apprec ...

Swapping out one variable for another

After tweaking my code a bit, I'm still struggling to get it right. User input: !change Hi var A = "Hello" if (msg.content.includes ('!change')) { A = msg.content.replace('!change ', ''); } msg.send(A); //the change ...

How can I make my navbar stay fixed in place and also activate the transform scale functionality?

After fixing the position of my navbar with the class "top," I noticed that the transform property scale does not work on the div element I applied. The hover effect on the box only works when I remove the position from the navbar. This is the HTML code: ...

Issues with triggering the success block in AngularJS and Node.js Express when using $http.get

As a beginner in the world of AngularJS and Node.js, I'm facing an issue with my $http.get method. The problem is that the success callback block does not get executed when the request is successful, whereas the error callback works just fine when the ...

An error occurred while trying to access the object null in React-Native, specifically when evaluating 'this.state.token'

I encountered an error while trying to execute a class in a view: When running the class, I received the following error message: null is not an object (evaluating 'this.state.token') The problematic class that I'm attempting to render: c ...

Using array.map() in React does not display elements side by side within a grid container

I'm currently working with React and material-ui in order to achieve my goal of displaying a grid container that is populated by an array from an external JavaScript file. The challenge I am facing is getting the grid to show 3 items per row, as it is ...

Can users be prevented from bookmarking a particular web page?

I'm working on a Python (Django) webpage and I need to prevent users from being able to bookmark a certain page. Is there a way to do this? ...

Guide on using jQuery to dynamically update a section of an ejs template following an AJAX request in ExpressJS

I'm currently struggling to figure out how to dynamically update a portion of the DOM using EJS after a jQuery ajax call. The issue arises with a live search feature that successfully sends a request to the server, searches the database, and returns a ...