javascript 如何在 AngularJS 中以编程方式触发表单提交?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27690230/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:50:12  来源:igfitidea点击:

How to trigger form submit programmatically in AngularJS?

javascriptangularjshtmlforms

提问by Pavel Voronin

From Angular's documentation it follows that ngSubmitis a preferred way of submitting a form. All pending operations are immediately finished and $submittedflag is set as well. Whereas listening to ngClickevent does not have the same effect.

从 Angular 的文档可以看出ngSubmit是提交表单的首选方式。所有挂起的操作都会立即完成并$submitted设置标志。而侦听ngClick事件没有相同的效果。

Now I need to submit a form with hotkeys having all the goodies of ngSubmitapproach. Hence I need some way to trigger standard submit workflow.

现在我需要提交一个带有热键的表单,其中包含所有方法的优点ngSubmit。因此我需要一些方法来触发标准提交工作流程。

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:

我尝试submit()了 DOM 表单并且它有效,但是附加到范围的 angular 表单对象不包含对 DOM 表单的引用,因此我需要通过 jqLit​​e 访问它:

var frm = angular.element('#frmId');
frm.submit();

I didn't like this solution for accessing DOM in controller code so I created a directive:

我不喜欢这个在控制器代码中访问 DOM 的解决方案,所以我创建了一个指令:

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();
                };
            }
        }
    };
}

which extends form object with $submitmethod.

它用$submit方法扩展了表单对象。

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:

由于未知原因,这两种变体都不起作用。form.submit()尝试发送数据,不会阻止默认操作。


更新 1
事实证明,Angular 侦听具有type="input".
最终我决定触发该元素的点击事件:

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?

此功能是否有任何开箱即用的解决方案?

采纳答案by non4me

Just use event .triggerHandler('submit') on form element.

只需在表单元素上使用 event .triggerHandler('submit') 即可。

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);   
              }
            })
        }
    };
}]);

Look at http://jsfiddle.net/84bodm5p/

看看http://jsfiddle.net/84bodm5p/

回答by nguyên

app.directive("form", function(){
     return {
        require: 'form',
        restrict: 'E',
        link: function(scope, elem, attrs, form) {
            form.doSubmit = function() {
                form.$setSubmitted();
                return scope.$eval(attrs.ngSubmit);
            };
        }
    };
});

Html:

网址:

<form name="myForm" ng-submit="$ctrl.submit()" novalidate>

Then call in controller

然后调用控制器

$scope.myForm.doSubmit();

回答by Shashank Agrawal

You can modify your directive code a bit like:

您可以像这样修改指令代码:

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() {
                    // Parse the handler of submit & execute that.
                    var fn = $parse(attr.ngSubmit);
                    $scope.$apply(function() {
                        fn($scope, {$event: e});
                    });
                };
            }
        }
    };
}

Here you don't have to add wu-submiteverywhere. ng-submitwill work.

在这里你不必wu-submit到处添加。ng-submit将工作。

Hope this helps!

希望这可以帮助!