AngularJS Forms

AngularJS  Forms

AngularJS has some features for binding data of HTML (Hyper Text Transfer Language) from input fields to the model object ($scope). These features make it understandable to work with forms. Controls (input, select, textarea) are ways for a user to enter to enter data. Forms are a collection of controls for the purpose of grouping related controls together.

Simple Form

The Forms and controls provide validation services, so that the user can be noted of invalid input before submitting of a form. A Form also provides a better user interface than server-side validation alone because the user gets instant output on how to correct the error.

Angularjs Form

You bind an input field to a model property utilizing the ng-model directive such as:

<input type="text" id="firstName" ng-model="myForm.firstName">

This binding is two types, that is if the $scope.myForm.firstname has a value set in the corresponding controller function, the input field always starts with that value. Basically, once the user types something into the text field that the value will be copied from the text into the $scope.myForm.firstName property.

Example

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
</head>
 
<body ng-app="myapp">
 
<div ng-controller="MyController" >
    <form>
        <input type="text" name="firstName" ng-model="myForm.firstName"> First name <br/>
        <input type="text" name="lastName"  ng-model="myForm.lastName"> Last name <br/>
    </form>
 
    <div>
        {{myForm.firstName}} {{myForm.lastName}}
    </div>
</div>
 
<script>
    angular.module("myapp", [])
            .controller("MyController", function($scope) {
                $scope.myForm = {};
                $scope.myForm.firstName = "Meraj";
                $scope.myForm.lastName  = "Ansari";
            } );
</script>
 
</body>
</html>

This example binds provides two input fields in the form to the $scope.myForm.firstName and second input is $scope.myForm.lastName properties.

Using the CSS classes into the Form

CSS classes provide styling of forms as well as controls, ngModel adds these:

  • ng-pending: This class provides any $asyncValidators are unfulfilled
  • ng-invalid: This class tells about the model is invalid
  • ng-valid-[key]: This class provides that, for each valid key added by $setValidity
  • ng-dirty: the This class provides how control has been interacting with
  • ng-touched: This class provide the control has been blurred
  • ng-untouched: This class provides the control has not been blurred
  • ng-invalid-[key]: This class is used for each invalid key added by $setValidity
  • ng-valid: This class tells about the model is valid
  • ng-pristine: the control has not  been interacting with yet
READ  AngularJS Ajax calls

CSS in AngularJS

These classes use the CSS to appear validity of every form control. Here some example, in this both user.name and user.email is required, but are they not entering with red background only after the input is blurred. This assures that the user is not distracted with an error until after interacting with the control, and unsuccessful to satisfy its validity.

For example:

 

<div ng-controller="ExampleController">
 <form novalidate class="css-form">
 Name: <input type="text" ng-model="user.name" required /><br />
 E-mail: <input type="email" ng-model="user.email" required /><br />
 Gender: <input type="radio" ng-model="user.gender" value="male" />male
 <input type="radio" ng-model="user.gender" value="female" />female<br />
 <input type="button" ng-click="reset()" value="Reset" />
 <input type="submit" ng-click="update(user)" value="Save" />
 </form>
 <pre>form = {{user | json}}</pre>
 <pre>master = {{master | json}}</pre>
 </div><style type="text/css">
 .css-form input.ng-invalid.ng-touched {
 background-color: #FA787E;
 }
.css-form input.ng-valid.ng-touched {
 background-color: #78FA89;
 }
 </style>
<script>
 angular.module('formExample', [])
 .controller('ExampleController', ['$scope', function($scope) {
 $scope.master = {};
$scope.update = function(user) {
 $scope.master = angular.copy(user);
 };
$scope.reset = function() {
 $scope.user = angular.copy($scope.master);
 };
$scope.reset();
 }]);
 </script>

Binding the Checkboxes

If you bind a checkbox (<input type=”checkbox”>) to a model property, model property will be set to true if the checkbox is checked and false if not.

If you want to different types values instead of true and false inserted into your model, you can use the ng-true-value and the ng-false-value directives, such as:

<input type="checkbox" ng-model="myForm.wantNewsletter"
                        ng-true-value="Yes" ng-false-value="No" >

Modifying built-in validators

After all AngularJS it uses $validators, you can easily replace or modified built-in validators, so you always find it necessary. Here some example shows you how to overwrite the validator in the email validator in input [email] from a custom directive so that it desires a specific top-level domain, example.com to be displayed.

<form name="form" class="css-form" novalidate>
  <div>
    Overwritten Email:
    <input type="email" ng-model="myEmail" overwrite-email name="overwrittenEmail" />
    <span ng-show="form.overwrittenEmail.$error.email">This email format is not valid!</span><br>
    Model: {{myEmail}}
    </div>
</form>