AngularJS - how to submit a form from the outside

How to trigger ng-submit?

Let's say you have HTML like this:

1
2
3
4
<form ng-submit="submit()">
    <input ng-model="formData" required />
</form>
<button type="submit">Submit from the outside</button>
1
2
3
4
//inside of a controller
$scope.submit = function(){
    //this is called when the form submits
}

This doesn‘t work. If the button was inside of the form element, this would work but it’s not always how you want to setup your HTML.

Is it possible to trigger ng-submit from outside of the form?

I tried some differnt ways but so far it doesn't seem to be possible to actually trigger the form submission that Angular is watching.

Do you have to trigger that?

Not really. You aren‘t really using browser’s native feature to POST the form anyway. ng-submit is nice but what it does are:

  • Find buttons that submit the form and listen to the click(ex: type=“submit”)
  • When those buttons get clicked, it runs the expression inside of the ng-submit, if the form is valid.

So it‘s not difficult to mimic what it’s doing. Please check this out.

You can access to the controller of the form directive easily

In the fiddle, you see I'm accessing to the controller of the form directive by just calling the name of the form on the $scope just like $scope[“formName”].

1
2
3
<form name="testForm" ng-submit="submit()>
    <input ng-model="formData" required />
</form>
1
2
3
if ($scope.testForm.$valid) {
    $scope.submit();
}

This let you check if the form is valid very easily.
So now you don't have to try to make the form trigger the submit, instead, you can check if the form is valid and do whatever you need to do, enjoy!