AngularJS: Automatically submitting HTML forms

Our yearlong delve into the sea that is Angular Js has kept our engineering team busy for quite some time now. Throughout this fun time of exploration there have been ups and downs, muddled coding snares caused by niche problems that are almost impossible to conform to the constantly looming “Angular Way”, and complicated problems that could be solved so easily you wished you had a Staples button just so you could push it for the “That was easy”.

One invaluable resource that has continually helped guide us through our use of this robust MVC framework is the vast Angular Js community, that has helped answer most of our questions, from questions about basic tutorials, to more overarching questions about best practices when structuring applications.

On one of our more recent Angular projects, we ran into an issue implementing a fairly common need among web applications – generating an auto submit form. After poking around Google and StackOverflow for a bit, surprisingly, there was a lot less information on this subject than expected. So, we decided to write a blog post on the subject, giving back to the AngularJS community, which has given so much to us.

Interestingly, this problem can be solved quite easily once you have a more comprehensive understanding about the Angular directive’s Link function. Here’s a good StackOverflow answer if you’re interested in some light reading: AngularJS: What is the need of the directive’s link function when we already had directive’s controller with scope?. However, if you’re anything like us then you’re probably solely interested in learning just enough to solve the immediate problem at hand, so for you, the main “gotcha” that you need to know is that the template for any directive is wrapped as an angular element, and can be accessed inside of the Link function using the angular.element() function.

The basic idea is simple, create a custom directive for your auto submit form, make the template for this directive a form element with the information you want to send, and control its rendering using an ng-if directive. Using ng-if is important in this instance because this directive doesn’t just show/hide a portion of the DOM tree, but actually removes/recreates it, allowing you to take advantage of the directives Link function. Then, inside of the link function for the auto submit form directive, grab the form element using the angular.element() function and submit it using the javascript function submit().

If the above paragraph didn’t completely explain it to you, please don’t worry, here is a nice, concrete example to help you solve this problem quickly should you ever run into it again in the future.