PachinSV PachinSV - 4 months ago 90
AngularJS Question

Error: [$rootScope:inprog] $digest already in progress

I'm trying so send a form (using a directive) when a property in the model changes (so I watch the property), but when I trigger the submit event, I get the error: "Error: [$rootScope:inprog] $digest already in progress", how can I avoid this error, here is my code:

app.directive("autoSubmit", function(){
return {
link: function(scope, element, attrs){

scope.$watch("valid", function(){
if(scope.valid == 1) {
console.log("send form");
element.triggerHandler("submit");
}
});
}
}
});


Heres is he plunk: http://plnkr.co/edit/cosJLkhUEKv55G8uU1Ea (to reproduce the error, just change the value of the textbox to 1)

Thanks in advance for your help.

Answer

The problem is that there is already a $digest cycle running (obviously watch one) when you try to trigger an event. So you should simply wait until its done and raise the event during the next one. You can $timeout service for that:

app.directive("autoSubmit", function($timeout) {
    return {
        link: function(scope, element, attrs) {
            scope.$watch("valid", function() {
                if (scope.valid == 1) {
                    console.log("send form");
                    $timeout(function() {
                        element.triggerHandler('submit');
                    })
                }
            });
        }
    }
});

Demo: http://plnkr.co/edit/bRXfi9kFVFICgFUFvtZz?p=preview

Another way around is to invoke ngSubmit function manually yourself using $parse service:

app.directive("autoSubmit", function($parse) {
    return {
        link: function(scope, element, attrs) {
            scope.$watch("valid", function() {
                if (scope.valid == 1) {
                    console.log("send form");
                    var submitHandler = $parse(attrs.ngSubmit)(scope);
                    if (submitHandler) {
                        submitHandler();
                    }
                }
            });
        }
    }
});

Demo: http://plnkr.co/edit/vNI8OwfnxSQJ6tQLpFqZ?p=preview