Angularjs ng maxlength directive

www‮figi.‬tidea.com

The ng-maxlength directive in AngularJS is used to set the maximum length of an input element. This directive can be used with any input element that accepts user input, such as text inputs, textareas, and password inputs.

Here is an example of using ng-maxlength with an input element:

<input type="text" ng-model="text" ng-maxlength="10">

In this example, the ng-model directive is used to bind the value of the input element to a scope variable called text. The ng-maxlength directive is used to limit the maximum number of characters that can be entered into the input to 10.

You can also use interpolation to dynamically set the value of ng-maxlength. Here is an example:

<label>
  Enter a title for your post:
  <input type="text" ng-model="title" ng-maxlength="{{ maxLength }}">
</label>
<p ng-show="title.length === maxLength">Maximum length reached!</p>
$scope.maxLength = 50;

In this example, the value of ng-maxlength is set to the value of the maxLength scope variable, which is set to 50 in the controller. The ng-show directive is used to conditionally show a paragraph element when the length of the title input is equal to the maximum length.

You can also use the $error object to check if the input has exceeded the maximum length. Here is an example:

<label>
  Enter your phone number:
  <input type="tel" ng-model="phoneNumber" ng-maxlength="10">
  <p ng-show="form.phoneNumber.$error.maxlength">Phone number is too long!</p>
</label>

In this example, the ng-maxlength directive is used to limit the maximum length of the phone number input to 10. The form.phoneNumber.$error.maxlength expression is used to check if the input has exceeded the maximum length, and the paragraph element is conditionally shown when the expression is true. Note that the form object is automatically created by AngularJS when the form containing the input is initialized.