The Directive cannot be refreshed as a result of the ongoing "$digest already in progress" error

Within my controller, I have set a default value for a variable called "data". In my original project, I am using CouchCorner to retrieve data from a CouchDB and update the value of this variable.

Inside a directive, I am watching the variable data and updating the corresponding element. However, I encountered an issue where I received the error "$digest already in progress", causing the directive not to update correctly. Despite researching extensively on the $digest problem, I could not find a suitable solution that addressed my specific issue.

I have created a jsFiddle example, which uses $timeout instead of making an actual CouchDB request: http://jsfiddle.net/cwesM/4/

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

function Ctrl($scope, $timeout) {
$scope.data="Initial";

$timeout(function(){
    $scope.data="Updated"}, 1)
}

App.directive('chart', function(){
    return{
        restrict: 'E',
        link: function(scope, elem, attrs){
            scope.$watch(attrs.ngModel, function(v){
                alert(v)
                elem.html("Data="+v);
            });
        }
   };
});

The script changes the initial value of "data" to "Updated" after 1ms. However, the directive does not get updated even though the $watch function is being executed. Interestingly, removing the alert() function causes everything to work as expected.

How can I prevent the $digest collision from occurring?

Answer №1

Check out the code snippet shared on stackoverflow.com/a/17510699 (Answered by @Dor Cohen).

I can assist you in integrating it with your existing code.

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

function Ctrl($scope, $timeout) {
    $scope.data = "Initial";
    $timeout(function () {
        $scope.data = "Updated"
    }, 1);

    $scope.alert = function (info) {
        alert(info);
    }

    $scope.safeApply = function (fn) {
        var phase = this.$root.$$phase;
        if (phase == '$apply' || phase == '$digest') {
            if (fn && (typeof (fn) === 'function')) {
                fn();
            }
        } else {
            this.$apply(fn);
        }
    };
}

App.directive('chart', function () {
    return {
        restrict: 'E',
        link: function (scope, elem, attrs) {
            scope.$watch(attrs.ngModel, function (v) {
                scope.safeApply(function () {
                    alert(v);
                });
                elem.html("Data=" + v);
            });
        }
    };
});

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 search functionality is malfunctioning within the JavaScript table

I am working with a table that I want to filter based on input values. However, the current filtering function is not working as expected. I have utilized an onkeyup function for the filtering process. For more details and a live example, check out the jsf ...

What is causing my AJAX function to malfunction and throwing an exception for undefined data objects?

I am having trouble with my ajax query in my code. Even though it is returning the required data, it is not displaying properly within the HTML code. I have a common header and footer (PHP) for all other files. Despite my efforts to resolve this issue by s ...

Ways to attach an item using its lower point instead of its upper coordinate

I am currently working on a poker table project using React. As of now, I have player components that need to be strategically positioned around the table. https://i.sstatic.net/gX9Ij.png One challenge I'm facing is that when the screen attribute ch ...

My data is not appearing with ng-repeat or ng-bind

One issue I am encountering is that my ng-repeat / ng-bind is not displaying the data within $scope.articles, even though I am getting the expected data in the console. To help identify the problem more easily, I have created a code snippet below: var A ...

What is the method for assigning a string to module variable definitions?

As someone new to TypeScript and MVC, I find myself unsure if I am even asking the right questions. I have multiple TypeScript files with identical functionality that are used across various search screens. My goal is to consolidate these into a single fil ...

Send multiple input groups using Ajax POST requests

I need help setting up a form with 4 groups of checkboxes for refining search results. My goal is to send an array for each checkbox group that contains the IDs of the currently selected checkboxes. $.ajax({ url: "/stay_in_belfast/accommodation", t ...

Retrieve JSON Data Using Angular in a Wordpress Environment

I need assistance with displaying a JSON Array in <li>'s within a Wordpress Template. Here is the specific JSON file: I am completely unfamiliar with how to achieve this. This is the HTML code I have: <div ng-app="appExtern" ng- ...

Troubles with AJAX and jQuery

<html> <head> <title>Ajax Example</title> <script type="text/JavaScript" src="jquery-1.5.1.min.js"></script> <script type="text/JavaScript"> function fetchData() { $.ajax({ type: "GET", url: "htt ...

Pressing "Enter" initiates the submission of the form

My webpage contains a stylish GIF displayed as a button within a div. The script inside the div triggers a click event when the ENTER key is pressed, using $(this).click(). This click action has its own functionality. Everything functions smoothly in Fire ...

Is there a way to create a new prettyphoto window by clicking on a link within the original prettyphoto window?

I have an HTML table that is dynamically constructed on the server side using AJAX. The table is displayed using prettyphoto, everything works fine up to this point. However, the last column of the table contains a link that should open an image using pret ...

Two states each offering a distinct perspective

I am currently working on modularizing my application using angular-ui-router to create a website with two states: main and checkout. In the main state, I want to have multiple "section" tags defined as ui-view items. However, it seems like there is an iss ...

Stop the page from scrolling when a modal is displayed in React

I've encountered an issue with my custom modal component where the background stops scrolling when the modal is open. Initially, I attempted to solve this by using the following code: componentDidMount() { document.body.style.overflow = 'hi ...

Turning off the transpiler in Vue Webpack to simplify the debugging process

Debugging in Vue can be quite challenging, especially when it comes to setting breakpoints and stepping through the code. The issue seems to stem from the transpiling of javascript ES6/ES2015/ES2016/ES2017 to ES5. While source maps provide some assistance, ...

Steps for automatically retrying a failed expect statement in Jest

In my React application, I am utilizing Jest for performing unit testing. One aspect of my application involves a Material UI date picker with next and previous buttons. The selected date is displayed in the browser URL. Each time the user clicks on the ne ...

What is the best way to display a Bootstrap toggle?

I am facing an issue with a Bootstrap toggle in a Handlebars template. When the page initially loads, the toggle is visible, however, after re-templating the Handlebars template that contains the toggle, it disappears. Before Re-Template: Initial code : ...

Using ng-bind-html does not offer protection against cross-site scripting vulnerabilities

I utilized ng-bind-html to safeguard against cross site scripting vulnerabilities. I came across information about sanitization and engaged in a discussion at one forum as well as another informative discussion. However, I encountered an issue where it di ...

Why is this regular expression failing to match German words?

I am attempting to separate the words in the following sentence and enclose them in individual span elements. <p class="german_p big">Das ist ein schönes Armband</p> I came across this: How to get a word under cursor using JavaScript? $(&ap ...

Is it possible to remove the "disabled" attribute using JS, but the button remains disabled?

There are two buttons on my page: the first one is currently disabled, and the second one is supposed to enable the first button. That's the plan. Button 1: $(document).ready(function() { $('#click').click(function() { document.getE ...

What is the best way to display the HTML content being received from the database in the DOM?

I have received an object in this format [ { "BET": 57630343, "CUSTOMER": 181645, "SPORT": "MLB", "XX_FILL OPEN": "<button class=\"btn\" onclick=\"fillOpen(57630343)\">Fill Open</button>", "XX_VIEW": n ...

Navigating through a JSON object in JavaScript by employing regular expressions

Is there a way to extract the "Value" of elements "Data1", "Data2", "Data3", "Data4" from a JSON object without resorting to regex? I've heard that using regex with JSON is not recommended. <script> abc = { "model": { ... } } </script> ...