AngularJS is currently in the process of conducting a $digest, please be patient

I am currently facing the common error message which says "$digest already in progress."

Is there a workaround that does not involve using scope.$apply?

Any assistance would be greatly appreciated. Thank you!

directive('ngUsername', ['$http', function($http) {
return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, elm, attr, ctrl) {
        //when the scope changes, check the email.
        scope.$watch(attr.ngModel, function(value) {
            $http.get('http://tagsy.co/api/username?token=' + apiToken + '&username=' + value).success(function(data) {
                scope.$apply(function(s) {
                    ctrl.$setValidity('uniqueUsername', data.unique);
                });
            });
        });
    }
}
}]);

<input type="text" name="username" ng-model="username" placeholder="Username" ng-minlength="3" ng-maxlength="15" ng-pattern="/^[A-Za-z0-9]+$/" autocomplete="off" ng-username required/>

<div ng-show="registerForm.username.$dirty && registerForm.username.$invalid">
    <span class="error" ng-show="registerForm.username.$error.required">Please choose a username.</span>
    <span class="error" ng-show="registerForm.username.$error.minlength">Username is too short.</span>
    <span class="error" ng-show="registerForm.username.$error.maxlength">Username is too long.</span>
    <span class="error" ng-show="registerForm.username.$error.pattern">Username can only be letters and numbers.</span>
    <span class="error" ng-show="registerForm.username.$error.uniqueUsername">Username is already taken.</span>
</div>

Answer №1

If you want to check if a cycle is already in progress before manually starting it, you can use the $scope.$$phase property. When $scope.$$phase is not set, it is safe to proceed and use $apply:

scope.$watch(attr.ngModel, function(value) {
  $http.get('http://tagsy.co/api/username?token=' + apiToken + '&username=' + value).success(function(data) {
    if (!scope.$$phase)
        scope.$apply(function(s) {
                ctrl.$setValidity('uniqueUsername', data.unique);
        });
    else
      ctrl.$setValidity('uniqueUsername', data.unique);
  });
}

To avoid redundancy in your code or simplify it, you may consider creating a helper function like this:

function safeApply($scope, applyFn) {
    if(!$scope.$$phase) $scope.$apply(applyFn)
    else applyFn();
}

scope.$watch(attr.ngModel, function(value) {
  $http.get('http://tagsy.co/api/username?token=' + apiToken + '&username=' + value).success(function(data) {
    safeApply(scope, function() {
      ctrl.$setValidity('uniqueUsername', data.unique);
    });
  });
}

Edit: Please note that in this particular case, using $http (and most angular services) will handle this process for you automatically.

Answer №2

After invoking $http.[verb], the response (whether successful or encountering an error) will trigger a $rootScope.$digest() to run automatically. It is unnecessary to include $scope.$apply within this 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

What is the best way to deactivate a hyperlink on a widget sourced from a different website?

Is there a way to remove the link from the widget I embedded on my website without access to other editing tools besides the HTML code provided? For instance, we have a Trustpilot widget at the bottom of our page that directs users to Trustpilot's web ...

Issue encountered while attempting to execute express through node

Currently, I am attempting to initiate a basic server on my Mac in order to access a file from localhost. My server file consists of the following code with Node and Express installed: var express = require('express'), app = express(); app.use ...

Building a personalized mapping system with the Google Maps API

I recently came across a cool feature in Google maps that allows users to add custom options to their website. How can I create something similar, where an info box pops up when you click on a location on the map? Check out this link for an example: If y ...

Develop a payment confirmation session using Stripe and Node.js

I have set up a POST request using Stripe to handle customer payments let paymentData = { errorMsg:'', key: process.env.STRIPE_PUBLIC_KEY } const session = await stripe.checkout.sessions.create({ payment_method_types: ...

Utilize a separate function within the ngOnInit() lifecycle hook

Currently, I am developing a mapping application using OpenLayers (4.6.5) within Angular (6). In order to execute requests and retrieve GeoJSON files, I am utilizing a French API made available by the French government. Previously, I successfully implemen ...

Text alignment issues cause animation to vanish

Utilizing particles.js, I set up a full-screen particle effect by specifying the animation to be full-screen with height: 100vh;. This worked perfectly as intended. However, when attempting to add text on top of the particle animation and center it vertica ...

Retrieving parameters from the URL in Angular

I'm facing an issue with my app. I am currently using a factory to manage data for two controllers. When I click on a link that redirects me to another view with a specific URL, I want to reuse the last tag in the URL by slicing it like this: window. ...

In the world of Node.js and Java, the concepts of "if"

Here is a code snippet that I am working with: var randFriend = friendList[Math.floor(Math.random() * friendList.length)]; if (randFriend == admin) { //Do something here } else if (randFriend != admin) { client.removeFriend(randFriend); } I am tr ...

Adjust the Highcharts semi-pie design by eliminating the gap between the pie and the legend

I'm having trouble adjusting the spacing between the bottom of a semi circle donut chart in Highcharts and the legend below it. Despite my efforts, I have not been successful in reducing this gap. Here is the basic chart I am currently working on: h ...

It seems that the JavaScript object is producing varied values in distinct locations despite no alterations made in between

I've encountered a puzzling issue where a variable is returning different values within a function, despite no modifications being made to it. This problem arises in a form component created using Vue.js (v2) that triggers a Vuex action. While I beli ...

What is the method to apply a class exclusively to an img tag?

While using the Cycle2 Carousel plugin, I encountered an issue with the class being set for my thumbnails. The plugin sets the .cycle-pager-active class for both images and divs, which is not ideal. I attempted to fix this by adding 'img' before ...

Issue with variable causing ng-maxlength not to function as intended

I am attempting to utilize the ng-maxLength directive in order to set a maximum length for my input variables. function ValidatorCtrl($scope, $timeout) { $scope.name = "Star"; $scope.$metadata={}; $scope.$metadata.isRequired = true; $scope.$metada ...

What is the best way to initiate a class constructor with certain parameters left out?

Currently, I am facing a challenge while trying to pass various combinations of arguments to a class constructor. The constructor has 2 optional arguments. Here is the code snippet: class MyClass { foo(a, b) { return new MyClass(a, b); } bar( ...

JavaScript inserted into debug console by developer

Is there a method to troubleshoot code that has been added through the firefox developer console terminal? For example, I added document.onkeydown = function(event) { // code logic for checking keys pressed } If only I could determine which .js file t ...

Are you having difficulty displaying an alert box for invalid login information in a React application?

I am encountering an issue with my code where I want to display an alert box if the username and password do not match. Currently, when sending a post request from React (using axios) to NodeJS to validate the email and password, everything works correctly ...

Unveil the content of a string by applying Base64 decoding in AngularJS

After encrypting a token sent from JAVA code to Angular using Base64 encryption, the next step is decryption: String token = "1345BCHCNB"; Cipher ecipher = Cipher.getInstance("AES"); String mykey = "1234567891234567"; SecretKey key = new SecretKey ...

Is there a way to automatically assign an index to ng-show values in AngularJS?

Why is the function not working? <div ng-repeat="report in reports track by $index"> <div ng-model="myDiv{{ $index }}" ng-show="myDiv{{ $index }}">{{ report }} {{ index }}</div> </div> How to make it work correctly? <div n ...

Having trouble with Pixastic - jQuery plugin not functioning properly?

I'm encountering an issue with the Pixastic jQuery plugin. I've been able to successfully use it as a standalone library, but when trying to integrate it with jQuery, it's not working. I followed the code from the documentation, but for some ...

I'm struggling to grasp the concept of map-reduce in MongoDB and it's leaving me feeling lost and

I'm currently exploring the potential of map-reduce in order to better grasp its utility. Within my database, I have a collection titled "actions" containing 100k documents structured like this: { "profile_id":1111, "action_id":2222 } My ai ...

ng-view is the culprit behind the website's fatal error

Encountering a "RangeError: Maximum call stack size exceeded" in the console while trying to recreate a basic routing example from w3schools. The crash seems to be linked to <div ng-view></div> in index.html. Despite making minimal changes from ...