I'd like to do a traditional form submit from within a controller. The scenario is that I want to hit a route on my web server and redirect to its response, which I can do with a regular form in HTML, but I also want to do some validation on its fields when the submit button is pressed, and if the validation fails, I don't want to do the route.
I'm aware of ng-valid, but I only want the validation to take place when the button is hit.
Is there a way to conditionally do a form submit from within a controller?
This is 'not the Angular' way to do it but you can submit the form using vanilla javascript. For example you can give the form an id and do:
document.getElementById('myForm').submit()
or if you have a submit button you can click it:
document.getElementById('myForm-submit').click()
I found that the first one did not keep the data bindings (I was using it on a project with a JQuery widget that had no Angular alternative), but the second one kept the bindings. I assume this has to do with how the JQuery widget was written.
You can see more about triggering forms with vanilla JS here:
How to submit a form using javascript?
How about just out-right disabling the submit button until the form is valid:
Take a look at this similar question I had: AngularJS Form Validation with Directives - "myform.$valid" not quite right for me
Expanding from @ReklatsMasters's answer, if you want to change a value before submitting the form, you could do like so...
You can add submit method to a FormController. I did so:
Sets the form to its $submitted state. This will also set $submitted on all child and parent forms of the form
https://docs.angularjs.org/api/ng/type/form.FormController#$setSubmitted
Did you try to use the ng-submit directive on your form? You may return true/false after your validation.
Controller
Html (you must not have an action attribute)