Submit form with ng-submit and trigger synchronous post request

Nat picture Nat · Mar 14, 2014 · Viewed 7.8k times · Source

I have a form that I want to trigger validation on when the user clicks submit. If the validation fails, then suitable error messages are displayed. This much works.

However if the validation passes I want the form to submit a synchronous POST request with full page reload as if the action and method parameters were set as usual.

How does one achieve trigger the normal post action (not AJAX) from the ng-submit function on the AngularJS scope?

My form of course looks basically like the following:

<form id="myForm" name="myForm" ng-submit="formAction(this, models)">
  ...
 <input type="submit" value="Submit">
</form>

The best I can think of is to mirror the contents of the form with another hidden form submitting that one, but there must be a better way!

TO CLARIFY: If validation passes, I need the form submission to essentially behave like a normal synchronous post form submission which lands the user at the page returned by the server from the post request.

Answer

jintoppy picture jintoppy · Mar 14, 2014

http://plnkr.co/edit/cgWaiQH8pjAT2IRObNJy?p=preview

Please check this plunkr

Basically what I am doing is passing the $event object. form is the target of the event object, and we can submit it.

function Ctrl($scope) {
    $scope.list = [];
    $scope.text = 'hello';
    $scope.submit = function($event) {
      if ($scope.text) {
        $scope.list.push(this.text);
        if(this.text === 'valid'){
          $event.target.submit();
        }
        $scope.text = '';

      }
    };
  }