![]() |
VOOZH | about |
AngularJS is a JavaScript-based framework. It can be used by adding it to an HTML page using a <script> tag. AngularJS helps in extending the HTML attributes with the help of directives and binding of data to the HTML with expressions. In this article, we'll learn about the AngularJS form.FormController.
The FormController keeps track of all its controls and nested forms, as well as the state of the forms. It acts as a mediator between HTML forms and AngularJS controllers, providing an API to access form-related functionality and data. It allows you to track the state and validity of form elements, handle form submissions, implement custom validations, and more.
The FormController class has the following methods:
We will understand the implementation of the different methods & properties associated with AngularJS FormController with the help of examples.
Syntax:
app.controller('FormController', function ($scope) {
$scope.formData = {}
$scope.submitForm = function () {
if ($scope.myForm.$valid) {
console.log('message!');
}
};
});
Example 1: In this example, we have used the ng-submit directive to trigger the form submission when the submit button is clicked. The form's submit event is handled by the submitForm function, which checks if the form is valid before logging a success message to the console.
Output:
Syntax:
$scope.submitForm = function () {
if ($scope.myForm.$valid) {
console.log('Form submitted successfully!');
$scope.myForm.$setPristine();
$scope.formData = {}; // Clear the form data
}
};
Example 2: In this example, we have used the setPristine() method that resets the form's pristine state, removing any error styles and validation flags after successfully submitting the form.
Output: