How to trigger form submit programmatically in AngularJS?

后端 未结 3 528
遇见更好的自我
遇见更好的自我 2021-01-06 00:48

From Angular\'s documentation it follows that ngSubmit is a preferred way of submitting a form. All pending operations are immediately finished and $submitted f

相关标签:
3条回答
  • 2021-01-06 01:17

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

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

    0 讨论(0)
  • 2021-01-06 01:27

    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-submit everywhere. ng-submit will work.

    Hope this helps!

    0 讨论(0)
  • 2021-01-06 01:29
    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();
    
    0 讨论(0)
提交回复
热议问题