AngularJS > Events

ng-submit events in AngularJS

How to bind AngularJS function onSubmit of the HTML form?

In previous posts, we learnt about onchange event operations in AngularJS. In this post, we shall learn onsubmit event operations and will try to understand how to bind AngularJS function on submit of the form.


ng-submit in AngularJS

In below <script> block, we have a controller with SubmitLogin function declared with the $scope. When this function is called, it simply sets FormData property of the $scope object with the data set in the HTML form, the same is written inside paragraph on the page.

    var app = angular.module("app", []);
    app.controller("NgSubmitController", ['$scope', function ($scope) {
        $scope.SubmitLogin = function () {
            // validate data, format data and send to server
            $scope.FormData = "Username: " + $scope.Username + ", Password: " +
<div ng-app="app" ng-controller="NgSubmitController">
    <form ng-submit="SubmitLogin()" >
            <tr><th colspan="2">Login</th></tr>
            <tr><td>Username: </td><td><input type="text" name="txtLogin"
ng-model="Username" placeholder="Enter username" /></td></tr>
            <tr><td>Password: </td><td><input type="password" name="txtPassword"
ng-model="Password" placeholder="Enter password" /></td></tr>
            <tr><td>&nbsp;</td><td><input type="submit" value="Submit" /></td></tr>
    <hr />
    <p>{{ FormData }}</p>

Read how to send data to server using $ method in AngularJS.

In above HTML block, notice the ng-submit directive whose value is set to "SubmitLogin()" function declared in the controller. Two text box with Username and Passwod is set with its respective ng-model.

When Submit button is clicked, because of its type="submit", it submits the current form but ng-submit directive prevents it from submitting to the form and instead executes the function assigned in it.

Important: Notice that we have not set action attribute of the <form> because if we specify that attribute, submit button will submit the formt to that page.

In this case, when the Submit button is clicked "SubmitLogin()" function executes and set ng-models value to FormData property that gets written on the page as FormData.

Note: Instead of using type="submit" for button, we could have also used type="button" but then we will need to use ng-click event to call "SubmitLogin()" function.

 Views: 12257 | Post Order: 42

Write for us

Hosting Recommendations