问题描述
从Angular的文档中可以看到, ngSubmit 是提交表单的首选方式.所有挂起的操作将立即完成,并且还将设置$submitted
标志.收听ngClick
事件的效果不同.
From Angular's documentation it follows that ngSubmit is a preferred way of submitting a form. All pending operations are immediately finished and $submitted
flag is set as well. Whereas listening to ngClick
event does not have the same effect.
现在,我需要提交一个包含所有具有ngSubmit
方法优点的热键的表单.因此,我需要一些触发标准提交工作流的方法.
Now I need to submit a form with hotkeys having all the goodies of ngSubmit
approach. Hence I need some way to trigger standard submit workflow.
我在DOM表单上尝试了submit()
,它可以工作,但是附加到scope的angular的form对象不包含对DOM表单的引用,因此我需要通过jqLite访问它:
I tried submit()
on DOM form and it worked, but angular's form object attached to scope contains no references to DOM form, thus I need to access it through jqLite:
var frm = angular.element('#frmId');
frm.submit();
我不喜欢这种在控制器代码中访问DOM的解决方案,所以我创建了一条指令:
I didn't like this solution for accessing DOM in controller code so I created a directive:
function wuSubmit() {
return {
require: 'form',
restrict: 'A',
link: function(scope, element, attributes) {
var scope = element.scope();
if (attributes.name && scope[attributes.name]) {
scope[attributes.name].$submit = function() {
element[0].submit();
};
}
}
};
}
使用$submit
方法扩展表单对象.
which extends form object with $submit
method.
这两个变体由于未知的原因而无法正常工作. form.submit()
尝试发送数据,但不会阻止默认操作.
更新1
事实证明,Angular侦听具有type="input"
的元素的click事件.
最终,我决定触发该元素的点击事件:
Both variants do not work for yet unknown reason. form.submit()
tries to send data, default action is not prevented.
Update 1
It turns out that Angular listens to click events of elements having type="input"
.
Eventually I decided to trigger click event for that element:
wuSubmit.$inject = ['$timeout'];
function wuSubmit($timeout) {
return {
require: 'form',
restrict: 'A',
link: function (scope, element, attributes) {
var submitElement = element.find('[type="submit"]').first();
if (attributes.name && scope[attributes.name]) {
scope[attributes.name].$submit = submit;
}
function submit() {
$timeout(function() {
submitElement.trigger('click');
});
}
}
};
}
是否有针对此功能的现成解决方案?
Is there any out of the box solution for this functionality?
推荐答案
只需在表单元素上使用事件.triggerHandler('submit').
Just use event .triggerHandler('submit') on form element.
myApp.directive("extSubmit", ['$timeout',function($timeout){
return {
link: function($scope, $el, $attr) {
$scope.$on('makeSubmit', function(event, data){
if(data.formName === $attr.name) {
$timeout(function() {
$el.triggerHandler('submit'); //<<< This is Important
//equivalent with native event
//$el[0].dispatchEvent(new Event('submit'))
}, 0, false);
}
})
}
};
}]);
查看 http://jsfiddle.net/84bodm5p/
这篇关于如何在AngularJS中以编程方式触发表单提交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!