ng-submit in AngularJS: Handle Form Submission with Example

โšก Smart Summary

ng-submit in AngularJS binds a controller function to the browser submit event of a form, so entered values are processed inside the controller and the page never reloads through a default POST.

  • ๐Ÿ”˜ Directive role: ng-submit binds an AngularJS expression to the submit event of a form element.
  • โ˜‘๏ธ No page reload: The default browser POST is suppressed unless the form carries an action attribute.
  • โœ… Worked example: A textbox plus Display() pushes each topic into the AllTopic array for ng-repeat.
  • ๐Ÿงช Validation gate: Pairing $valid with novalidate and ng-disabled blocks submission of incomplete data.
  • ๐Ÿ› ๏ธ Common mistake: Binding ng-click on the submit button beside ng-submit causes double submission.
  • ๐Ÿ“Š Version note: AngularJS support ended January 2022; modern Angular submits through (ngSubmit).

ng-submit directive in AngularJS binding a form submit event to a controller function

AngularJS ng-submit Directive

The ng-submit directive in AngularJS is used to bind the application to the submit event of the browser. So in the case of AngularJS on the submit event, you can carry out some processing within the controller itself and then display the processed information to the user.

Version note: AngularJS 1.x left Long Term Support on 31 December 2021, and the framework team confirms that AngularJS support officially ended in January 2022, so no releases or security patches follow. Every step and code block below is kept exactly as written, as the historical reference. New work belongs in modern Angular, which expresses the same idea as (ngSubmit) bound to a FormGroup.

How to Submit a Form in AngularJS using ng-submit

The processes of submitting information on a web page are normally handled by the submit event on the web browser. This event is normally used to send information which the user might have entered on a web page to the server for further processing like login credentials, form data, etc. The submission of information can be done through GET or POST request.

Letโ€™s take an Angular form submit example to see how to submit forms in AngularJS.

In our AngularJS form submit example, we are going to present a textbox to the user in which they can enter the topic which they want to learn. There will be a submit button on the page, which when pressed will add the topic to an unordered list.

The illustration below traces that flow, from the topic typed into the textbox, through the Submit button, to the list item appended underneath.

AngularJS form with a topic textbox, a Submit button and the resulting unordered list of topics
Submitting a Form in AngularJS using ng-submit

AngularJS Form Submit Example

Now, we will see an example of AngularJS form submit from Controller using ng-submit directive:

<!DOCTYPE html>
<html>
<head>

    <meta chrset="UTF 8">
    <title>Event Registration</title>
</head>

<body  ng-app="sampleApp">
<script src="https://code.angularjs.org/1.6.9/angular-route.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.min.js"></script>
<script src="https://code.angularjs.org/1.6.9/angular.js"></script>
<script src="lib/bootstrap.js"></script>
<script src="lib/bootstrap.css"></script>
<h1> Guru99 Global Event</h1>
<div ng-controller="AngularController">

    <form ng-submit="Display()">
        &nbsp;&nbsp;&nbsp;
        Enter which topic you would like to learn
        <input type="text"  ng-app="sampleApp" ng-model="Topic"><br>

        <input type="submit" value="Submit"/>

        <ul ng-repeat="topicname in AllTopic">
            <li>{{topicname}}</li>
        </ul>
    </form>
</div>

<script>
   var sampleApp = angular.module("sampleApp",[]);

    sampleApp.controller("AngularController",function($scope) {
        $scope.AllTopic=[];
        $scope.Display = function () {
            $scope.AllTopic.push($scope.Topic);
        }
    });
</script>
</body>
</html>

Code Explanation:

  1. We are first declaring our form HTML tag, which will hold the โ€œtext boxโ€ and โ€œsubmit buttonโ€ control as shown in the Angular form submit event example. We are then using the ng-submit AngularJS directive to bind the function โ€œDisplay()โ€ to our form. This function will be defined in our controller and will be called when the form is submitted.
  2. We have a text control in which the user will enter the Topic they want to learn. This will be bound to a variable called โ€˜Topicโ€™ which will be used in our controller.
  3. There is the normal submit button in AngularJS which the user will click when they have entered the topic they want.
  4. We have used the ng-repeat directive to display list items of the topics the user enters. The ng-repeat directive goes through each topic in the array โ€˜AllTopicโ€™ and displays the topic name accordingly.
  5. In our controller, we are declaring an array variable called โ€˜AllTopic.โ€™ This will be used to hold all the topics entered by the user in Step 2.
  6. We are defining the code for our Display() function which will be called whenever the user clicks the Submit button. Over here we are using the push array function to add the Topics entered by the user via the variable โ€˜Topicโ€™ into our array โ€˜AllTopic.โ€™

If the AngularJS form example code is executed successfully, the following Output will be shown when you run your code in the browser.
Output:

Browser output of the AngularJS ng-submit example showing the empty topic textbox and Submit button

To see the code working, first, enter a Topic name like โ€œAngularโ€ as shown above in the textbox and then click on the Submit button.

AngularJS ng-submit output after clicking Submit, with the entered topic added to the list

  • After the submit button is clicked, you will see the item which was entered in the textbox added to the list of items.
  • This is being achieved by Display() function, which is called when the submit button is pressed.
  • The Display() function adds the text to the array variable called โ€˜AllTopic.โ€™ And our ng-repeat directive goes through each value in the array variable โ€˜AllTopicโ€™ and displays them as list items accordingly.

ng-submit vs ng-click: Which One to Use

Both AngularJS directives can call the same controller function, yet they listen to different browser events. ng-submit sits on the <form> tag and reacts to the submit event, so it also fires when a user presses Enter inside a field. ng-click sits on a button and reacts only to a mouse click or an equivalent activation.

Aspect ng-submit ng-click
Host element The form tag Any clickable element
Event listened to submit, including the Enter key click only
Default browser POST Suppressed by the directive Still fires from a submit button
Access to form state Reads $valid and $invalid on the form controller No form context of its own
Natural fit Handing form data to a controller Toolbar buttons, links, modal triggers

Keyboard support usually settles the choice. A form wired with ng-click alone ignores the Enter key, which frustrates users filling a login box. Reserve ng-click for actions that are not form submissions, such as clearing a field or opening a dialog.

Why ng-submit Prevents the Default Browser Submit

A plain HTML form reacts to a submit event by serialising its fields and asking the browser to load a new page, which discards every value held in $scope. The ng-submit directive stops that from happening: it calls preventDefault() for you, so the expression runs and the current page stays in place. No $event argument and no manual call are required.

The suppression has one documented condition. According to the ngSubmit reference, the default action is prevented only while the form carries no action, data-action or x-action attribute. Add any of those and the browser navigates as usual after the handler finishes, which is the correct behaviour for a progressively enhanced server-rendered form and a surprise everywhere else.

Because the directive swallows the event object, read submitted values from the properties that ng-model wrote onto the scope, or pass them explicitly, as in ng-submit="Display(Topic)".

How to Validate a Form Before ng-submit Runs

The example above accepts an empty topic, because nothing checks the textbox first. AngularJS builds a form controller for every named form, and that controller exposes the flags needed to gate submission. Add novalidate so the browser leaves its own HTML5 bubbles switched off and AngularJS form validation takes over.

  1. Give the form a name. AngularJS publishes a controller of that name on the surrounding controller scope.
  2. Add novalidate to the form tag so native browser validation stays out of the way.
  3. Mark the fields, using required, ng-minlength, ng-maxlength or ng-pattern.
  4. Guard the handler with $valid, and pass the form controller in so the function can inspect individual fields.
  5. Disable the button with ng-disabled pointing at $invalid, which gives immediate visual feedback.
<form name="topicForm" ng-submit="topicForm.$valid && Display(topicForm)" novalidate>
    <input type="text" name="Topic" ng-model="Topic" required>
    <input type="submit" value="Submit" ng-disabled="topicForm.$invalid">
</form>

Two mistakes account for most reported problems with this pattern:

  • Double submission. Binding ng-click on the submit button while ng-submit sits on the form runs the handler twice, once per event. The official reference warns against combining the two handlers, so pick one.
  • Unexpected submits. Any button inside a form without type="button" raises the submit event. Mark cancel and reset buttons explicitly, otherwise they trigger the handler too.

Guarding on $valid is a convenience, not a security control. Values still have to be re-validated on the server before they are stored.

FAQs

Yes. A form holding an input or button of type submit raises the submit event when Enter is pressed inside a field, so the ng-submit expression runs without any extra key handler.

No. Only form elements raise the submit event that the directive listens for. Move ng-submit onto the form tag, or attach ng-click to the element you actually want to react to.

ng-submit passes no arguments. Read the scope properties that ng-model populated, or pass them in explicitly, for example ng-submit=”Display(Topic)” or ng-submit=”Display(topicForm)”.

Yes. Each form element gets its own form controller, so give every form a unique name and bind a separate handler. Sharing one function across forms invites scope collisions.

The handler fires either way, but a field without ng-model never writes its value to $scope, so the function cannot read it. Bind every input you plan to process.

Compile the form in a test, set the model value on the scope, trigger a submit event, then assert on the array or service call the handler produces. Karma with Jasmine remains the usual pairing.

Language models read the model shape and draft required, ng-pattern and ng-minlength attributes plus matching messages, which turns much AngularJS form validation work into a review step.

GitHub Copilot agent mode rewrites a template into (ngSubmit) with FormGroup and scaffolds the component class, yet the generated validators and async calls still need human review and tests.

Summarize this post with: