AngularJS 表单

在 AngularJS 中,表单是应用交互的一部分。AngularJS 提供了强大的功能来处理表单验证、数据绑定和提交等操作。你可以通过 ng-model 指令将表单元素与 AngularJS 的模型绑定,ng-submit 来绑定表单提交事件,并使用内置的验证指令来简化表单验证过程。

1. 表单绑定

表单元素与 AngularJS 数据模型的绑定通常通过 ng-model 指令完成。ng-model 指令将 HTML 表单控件与 AngularJS 的 $scope 数据模型绑定,使得视图和模型之间可以保持同步。

示例:表单绑定

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title>AngularJS 表单绑定</title>
</head>
<body ng-controller="formController">

    <h1>用户信息表单</h1>

    <form ng-submit="submitForm()">
        <label for="name">姓名:</label>
        <input type="text" id="name" ng-model="user.name" required />
        <br />

        <label for="email">电子邮件:</label>
        <input type="email" id="email" ng-model="user.email" required />
        <br />

        <button type="submit">提交</button>
    </form>

    <h2>提交的用户信息:</h2>
    <p>姓名:{{ user.name }}</p>
    <p>电子邮件:{{ user.email }}</p>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script>
        var app = angular.module('myApp', []);

        app.controller('formController', function($scope) {
            $scope.user = {};
            $scope.submitForm = function() {
                alert("表单已提交!");
            };
        });
    </script>

</body>
</html>

说明:

  • ng-model="user.name"ng-model="user.email" 将输入框与 $scope.user 对象绑定,形成双向数据绑定。
  • 表单提交时,ng-submit="submitForm()" 会调用 submitForm() 方法。

2. 表单验证

AngularJS 提供了内置的表单验证机制,可以通过不同的验证指令(如 requiredemailminlength 等)进行字段验证。

常见的表单验证指令:

  • required:字段是否必填。
  • email:验证电子邮件格式。
  • minlength / maxlength:验证输入长度。
  • pattern:使用正则表达式进行自定义验证。

示例:表单验证

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title>AngularJS 表单验证</title>
</head>
<body ng-controller="formController">

    <h1>注册表单</h1>

    <form name="registrationForm" ng-submit="submitForm()" novalidate>
        <label for="username">用户名:</label>
        <input type="text" id="username" ng-model="user.username" required />
        <span ng-show="registrationForm.username.$touched && registrationForm.username.$invalid">用户名是必填项!</span>
        <br />

        <label for="email">电子邮件:</label>
        <input type="email" id="email" ng-model="user.email" required />
        <span ng-show="registrationForm.email.$touched && registrationForm.email.$invalid">请输入有效的电子邮件地址!</span>
        <br />

        <button type="submit" ng-disabled="registrationForm.$invalid">提交</button>
    </form>

    <h2>表单数据:</h2>
    <pre>{{ user }}</pre>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script>
        var app = angular.module('myApp', []);

        app.controller('formController', function($scope) {
            $scope.user = {};

            $scope.submitForm = function() {
                if ($scope.registrationForm.$valid) {
                    alert("表单提交成功!");
                } else {
                    alert("表单验证失败!");
                }
            };
        });
    </script>

</body>
</html>

说明:

  • ng-model="user.username"ng-model="user.email" 分别绑定了用户名和电子邮件字段。
  • required 属性用于验证字段是否必填。
  • 使用 ng-show 显示验证错误消息。
  • ng-disabled="registrationForm.$invalid" 禁用提交按钮,直到表单验证通过。

3. 表单控制器

AngularJS 自动创建一个表单控制器,用于管理表单的状态。你可以通过表单控制器来访问表单字段的状态(如有效性、是否被触摸等)。例如,$valid$invalid 属性用于检查表单是否有效。

表单状态属性:

  • $valid:当表单有效时为 true,否则为 false
  • $invalid:当表单无效时为 true,否则为 false
  • $dirty:当表单字段被修改时为 true,否则为 false
  • $pristine:当表单字段没有被修改时为 true,否则为 false
  • $touched:当表单字段获得焦点并离开时为 true,否则为 false
  • $untouched:当表单字段未被触摸时为 true,否则为 false

示例:表单控制器

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title>AngularJS 表单控制器</title>
</head>
<body ng-controller="formController">

    <h1>用户登录</h1>

    <form name="loginForm" ng-submit="submitForm()">
        <label for="username">用户名:</label>
        <input type="text" id="username" ng-model="user.username" required />
        <br />

        <label for="password">密码:</label>
        <input type="password" id="password" ng-model="user.password" required />
        <br />

        <button type="submit" ng-disabled="loginForm.$invalid">登录</button>
    </form>

    <h2>表单状态:</h2>
    <pre>{{ loginForm.$valid }}</pre>
    <pre>{{ loginForm.$invalid }}</pre>
    <pre>{{ loginForm.$dirty }}</pre>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script>
        var app = angular.module('myApp', []);

        app.controller('formController', function($scope) {
            $scope.user = {};

            $scope.submitForm = function() {
                alert("表单提交成功!");
            };
        });
    </script>

</body>
</html>

说明:

  • loginForm.$validloginForm.$invalid 用于检查表单的有效性。
  • loginForm.$dirty 显示表单字段是否被修改。

4. 自定义验证

除了内置验证,AngularJS 还允许你创建自定义验证规则。例如,你可以使用 ng-pattern 来验证字段是否符合特定的正则表达式。

示例:自定义验证

<!DOCTYPE html>
<html ng-app="myApp">
<head>
    <title>AngularJS 自定义验证</title>
</head>
<body ng-controller="formController">

    <h1>密码验证</h1>

    <form name="passwordForm" ng-submit="submitForm()">
        <label for="password">密码:</label>
        <input type="password" id="password" ng-model="user.password" ng-pattern="/^[a-zA-Z0-9]{6,12}$/" required />
        <span ng-show="passwordForm.password.$touched && passwordForm.password.$invalid">
            密码必须是 6-12 个字母或数字!
        </span>
        <br />

        <button type="submit" ng-disabled="passwordForm.$invalid">提交</button>
    </form>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
    <script>
        var app = angular.module('myApp', []);

        app.controller('formController', function($scope) {
            $scope.user = {};

            $scope.submitForm = function() {
                if ($scope.passwordForm.$valid) {
                    alert("表单提交成功!");
                } else {
                    alert("表单验证失败!");
                }
            };
        });
    </script>

</body>
</html>

说明:

  • ng-pattern="/^[a-zA-Z0-9]{6,12}$/" 用于验证密码是否为 6-12 位的字母或数字。
  • 如果输入不符合规则,则会显示错误消息。

总结

  • ng-model 用于将表单元素与 AngularJS 数据模型绑定。
  • ng-submit 用于提交表单。
  • AngularJS 提供了内置验证指令(如 requiredemailminlength)来简化表单验证过程。
  • 可以通过表单控制器访问表单的状态,例如 $valid$invalid 等。
  • 可以使用 ng-pattern 创建自定义验证规则。

AngularJS 的表单处理功能极大地简化了开发,尤其是在表单验证、数据绑定和提交方面。