A simple introduction to forms in AngularJS

  • 2021-07-06 09:47:59
  • OfStack

AngularJS Form

An AngularJS form is a collection of input controls.

HTML Control

The following HTML input elements are referred to as HTML controls:

input Element
select element
button element
textarea Element

HTML Form

HTML forms typically coexist with HTML controls.

AngularJS Form Instance

First Name:

Last Name:


RESET

form = {"firstName":"John","lastName":"Doe"}

master = {"firstName":"John","lastName":"Doe"}

Application code:


<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
</head>
<body>

<div ng-app="myApp" ng-controller="formCtrl">
 <form novalidate>
 First Name:<br>
 <input type="text" ng-model="user.firstName"><br>
 Last Name:<br>
 <input type="text" ng-model="user.lastName">
 <br><br>
 <button ng-click="reset()">RESET</button>
 </form>
 <p>form = {{user }}</p>
 <p>master = {{master}}</p>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
 $scope.master = {firstName:"John", lastName:"Doe"};
 $scope.reset = function() {
  $scope.user = angular.copy($scope.master);
 };
 $scope.reset();
});
</script>

</body>
</html>

Run results:

First Name:

Last Name:


RESET

form = {"firstName":"John","lastName":"Doe"}

master = {"firstName":"John","lastName":"Doe"}

Note: The novalidate attribute is added in HTML 5. Default authentication using the browser is disabled.

Instance parsing

The ng-app directive defines the AngularJS application.

The ng-controller directives define the application controller.

The ng-model directive binds two input elements to the model's user object.

The formCtrl function sets the initial value of the master object and defines the reset () method.

The reset () method sets the user object equal to the master object.

The ng-click instruction calls the reset () method and is called when a button is clicked.

The novalidate attribute is not required in the application, but you need to use it in the AngularJS form to override the standard HTML 5 validation.

The above is the AngularJS form data collation, follow-up to continue to supplement, hoping to help programming students.


Related articles: