Open In App

AngularJS input Directive

In this article, we will see how the input Directive in AngularJS can be utilized to change the default behavior of <input> elements. This can be done with the help of the ng-model attribute present inside the <input> element. <input> is an HTML tag that is used to get user data using the input.ng-model, which is an angular directive that is used for data binding(i.e., reference to the input element is provided by the ng-model). These both are combined to modify the input field. 

Syntax:



<input ng-model="name">

The following states are established to the input field whose value is true for the following:

The value for each state represents the boolean value, i.e. either true or false.

Example 1: This example illustrates the $valid state for the required input field in a form.






<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
    <title>AngularJS input Directive</title>
</head>
  
<body ng-app="" style="text-align:center;">
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
    <h3>AngularJS input Directive</h3>
    <form name="form1">
        <input name="var1" ng-model="var1" required>
    </form>
    <p>{{var1}}</p>
    <p>
        The state of $valid is {{form1.var1.$valid}}
    </p>
</body>
</html>

Output:

 

For the above-mentioned input directive, there are few CSS classes are added, which are described below:

The classes are removed if the value is false.

Example 2: If the input field is used along with the required attribute, then the valid (when there is an input it is set to true) and invalid (when there is no input it is set to true) states are established. The classes are removed if the value is false. 




<!DOCTYPE html>
<html>
  
<head>
    <title> AngularJS input Directive</title>
    <style>
        input.ng-invalid {
            background-color: green;
        }
  
        input.ng-valid {
            background-color: yellow;
        }
    </style>
  
    <script src=
    </script>
</head>
  
<body ng-app="" style="text-align:center;">
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
    <h3>AngularJS input Directive</h3>
    <form name="form1">
        <input name="var1" ng-model="var1" required>
    </form>
    <p>{{var1}}</p>
    <p>
        The state of $valid is
        {{form1.var1.$valid}}
    </p>
</body>
</html>

Output:

 


Article Tags :