Pac*_*nSV 13 javascript submit angularjs angularjs-directive
我正在尝试当模型中的属性发生更改时发送一个表单(使用指令)(所以我看属性),但是当我触发提交事件时,我收到错误:"错误:[$ rootScope:inprog] $ digest已在进行中",如何避免此错误,这是我的代码:
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");
}
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
Heres是他的插件:http://plnkr.co/edit/cosJLkhUEKv55G8uU1Ea(重现错误,只需将文本框的值更改为1)
在此先感谢您的帮助.
dfs*_*fsq 14
问题是,watch
当您尝试触发事件时,已经有$ digest周期运行(显然是一个).所以你应该等到它完成并在下一个事件中提升事件.你可以$timeout
为此服务:
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');
})
}
});
}
}
});
Run Code Online (Sandbox Code Playgroud)
另一种方法是ngSubmit
使用$parse
服务自己手动调用函数:
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();
}
}
});
}
}
});
Run Code Online (Sandbox Code Playgroud)