AngularJS – ngMaxlength 指令

angularjsweb developmentfront end technology更新于 2026/1/7 1:22:17

AngularJS 中的 ngMaxlength 指令 为 ngModel 添加了 maxlength 验证器。此指令主要用于控制基于文本的输入,但也可用于控制基于自定义文本的控件。

如果 ngModel.$viewValue 的值大于通过计算 ngMaxlength 属性值中定义的 Angular JS 表达式得到的整数值,则此验证器会设置 ma​​xlength 错误键。

语法

<element ng-maxlength="expression">..content..</element>

示例 − ngMaxlength 指令

在 Angular 项目目录中创建文件"ngMaxlength.html",并复制粘贴以下代码片段。

<!DOCTYPE html>
<html>
   <head>
      <title>ngMaxlength Directive</title>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
   </head>

   <body ng-app="app" style="text-align: center;">
      <h1 style="color: green;">
         Welcome to Tutorials Point
      </h1>
      <h2>
         AngularJS | ngMaxlength Directive
      </h2>

      <div ng-controller="demo">
         <form name="form">
            <label for="maxlength">Input the text maxlength: </label>
            <input type="number" ng-model="maxlength" id="maxlength" />
            <br />
            <label for="input">This input is restricted by the current maxlength: </label>
            <input type="text" ng-model="model" id="input" name="input" ng-maxlength="maxlength" /><br />
            <br />
            input valid? = <code>{{form.input.$valid}}</code><br />
            model = <code>{{model}}</code>
         </form>
      </div>

      <script>
         angular.module("app", []).controller("demo", [
            "$scope",
            function ($scope) {
               $scope.maxlength = 5;
            },
         ]);
      </script>
   </body>
</html>

输出

要运行上述代码,只需转到您的文件并将其作为普通 HTML 文件运行即可。

观察输出,当输入文本的长度大于 ma​​xlength 时,输入 将变为无效。


相关文章