ng-submit – Handling form submission

Loading

In AngularJS, the ng-submit directive is used to handle form submissions. It ensures that the form is submitted properly without requiring an explicit JavaScript function call. Unlike the traditional onsubmit event in HTML, ng-submit prevents the default form submission behavior and allows you to handle the logic within your AngularJS controller.


Topics Covered

  1. What is ng-submit?
  2. Setting Up a Simple Form with ng-submit
  3. Validating Form Inputs Before Submission
  4. Disabling the Submit Button Until Form is Valid
  5. Handling Form Reset After Submission
  6. Submitting Forms Using $http (AJAX Request)
  7. Best Practices
  8. Conclusion

1. What is ng-submit?

ng-submit is an AngularJS directive that binds a function to the form submission event.
It prevents page reloads by stopping the default form submission behavior.
It allows form validation before executing the submit logic.
It works only on <form> elements, ensuring proper form handling.


2. Setting Up a Simple Form with ng-submit

Let’s start with a basic example of ng-submit in action.

Example: Simple Form Submission

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-controller="FormController">

<form name="userForm" ng-submit="submitForm()">
<label>Username:</label>
<input type="text" name="username" ng-model="user.username" required>

<button type="submit">Submit</button>
</form>

<p>{{ message }}</p>

<script>
var app = angular.module('myApp', []);
app.controller('FormController', function ($scope) {
$scope.user = {};
$scope.message = "";

$scope.submitForm = function () {
$scope.message = "Form submitted successfully!";
};
});
</script>
</body>
</html>

How It Works:

The form is bound to ng-submit="submitForm()".
When the submit button is clicked, submitForm() is called.
The function updates $scope.message with confirmation text.
There is no page refresh when the form is submitted.


3. Validating Form Inputs Before Submission

Form validation ensures that the data entered is correct before processing it.

Example: Form Validation with ng-submit

<form name="userForm" ng-submit="submitForm()" novalidate>
<label>Email:</label>
<input type="email" name="email" ng-model="user.email" required>

<div ng-show="userForm.email.$dirty && userForm.email.$invalid">
<span ng-show="userForm.email.$error.required">Email is required!</span>
<span ng-show="userForm.email.$error.email">Invalid email format!</span>
</div>

<button type="submit" ng-disabled="userForm.$invalid">Submit</button>
</form>

Explanation:

required and email attributes ensure proper validation.
Validation messages only appear when the user interacts with the field.
The Submit button is disabled until the form is valid.


4. Disabling the Submit Button Until Form is Valid

To prevent users from submitting an invalid form, we disable the submit button using:

htmlCopyEdit<button type="submit" ng-disabled="userForm.$invalid">Submit</button>
  • This ensures that the form cannot be submitted until all fields meet validation criteria.

5. Handling Form Reset After Submission

After submitting a form, it’s good practice to reset the fields.

Example: Resetting Form After Submission

<form name="userForm" ng-submit="submitForm()" novalidate>
<label>Name:</label>
<input type="text" name="name" ng-model="user.name" required>

<button type="submit" ng-disabled="userForm.$invalid">Submit</button>
</form>

<button ng-click="resetForm()">Reset</button>

<script>
app.controller('FormController', function ($scope) {
$scope.user = {};

$scope.submitForm = function () {
alert("Form submitted!");
$scope.user = {}; // Reset form data
$scope.userForm.$setPristine(); // Reset validation state
$scope.userForm.$setUntouched();
};

$scope.resetForm = function () {
$scope.user = {};
$scope.userForm.$setPristine();
$scope.userForm.$setUntouched();
};
});
</script>

Explanation:

ng-click="resetForm()" clears the form data.
$scope.user = {}; resets the model.
$scope.userForm.$setPristine(); resets the validation state.


6. Submitting Forms Using $http (AJAX Request)

In real-world applications, forms are submitted to a server using $http.

Example: Submitting Form Data to a Server

<form name="userForm" ng-submit="submitForm()" novalidate>
<label>Username:</label>
<input type="text" name="username" ng-model="user.username" required>

<button type="submit" ng-disabled="userForm.$invalid">Submit</button>
</form>

<p>{{ responseMessage }}</p>

<script>
app.controller('FormController', function ($scope, $http) {
$scope.user = {};
$scope.responseMessage = "";

$scope.submitForm = function () {
$http.post('https://example.com/api/submit', $scope.user)
.then(function (response) {
$scope.responseMessage = "Form submitted successfully!";
}, function (error) {
$scope.responseMessage = "Error submitting form!";
});
};
});
</script>

How It Works:

$http.post() sends the form data to a server.
On success, it displays a success message.
On failure, it displays an error message.

Leave a Reply

Your email address will not be published. Required fields are marked *