Angular onsubmit for form

I need the functionality of the onsubmit attribute on a form - namely when I call this onsubmit function, it must return truthy in order for the form to post. However I would like to do this with an angular function call, along the lines of:

<form id="form-submit-canvas" autocomplete="on" enctype="multipart/form-data" accept-charset="UTF-8" method="POST" onsubmit="{{FormSubmit.validate()}}" action="{{FormSubmit.SUBMIT_URL}}" novalidate>

However the above gives out errors about interpolation being used on onsubmit. I tried putting in ng-submit and it does not work since the action property I have set is overridden.


Solution 1:

Not sure if it's still valid for you, but as I've been fighting the similar problem.

Following answer brought me to the right track: https://stackoverflow.com/a/17769240/1581069

So, to sum up the steps required:

  1. you should call pure javascript (angular-free one) in your onsubmit, like (please note: if you return false there => form won't be submited):

    <form id="form-submit-canvas" ... name="fooForm" onsubmit="return externalValidate();" ...
    
  2. And implement the the method to hand-over to angular, like:

    function externalValidate(){
      return angular.element($("#form-submit-canvas")).scope().validate();
    }
    
    • where your validate() method should be just one you referred to previously (implemented in your angular controller).
    • and externalValidate() should be implemented outside of any angular-specific component.
  3. Moreover make sure sure to return correct result from the validate() method (to prevent form submission). Maybe something like:

    $scope.validate = function () {
      // TODO implement whatever magic you need prior to submission
    
      return $scope.fooForm.$valid;
    }
    

Solution 2:

Try using the ng-submit attribute instead of onsubmit. Related advise: Many attributes are not supported by Angular. You should find the ng- equivalent of the attribute you want to use to get Angular to react to them properly.

Example:

<form id="form-submit-canvas" autocomplete="on" enctype="multipart/form-data" accept-charset="UTF-8" method="POST" ng-submit="validate()" novalidate>
    ...
    <input type="submit" name="submit" value="Submit" />
</form>

Where the validate() method in ng-submit is a method declared on your $scope.

Here is a related tutorial: AngularJS Tutorial (ng-submit)