简体   繁体   中英

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.

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

当你启动一个进程并且不杀死它时你会收到摘要已经在进行中,为了解决这个问题,你必须在特定时间后使用$ timeout服务终止进程。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM