1 <!doctype html>
2 <html lang="en" ng-app="myApp">
3 <head>
4 <meta charset="UTF-8">
5 <meta name="viewport"
6 content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
7 <meta http-equiv="X-UA-Compatible" content="ie=edge">
8 <title>Document</title>
9 <script src="http://cdn.bootcss.com/angular.js/1.6.2/angular.min.js"></script>
10 <!--<script src="http://cdn.bootcss.com/angular.js/1.6.2/angular-messages.min.js"></script>-->
11 <style>
12 input.ng-invalid {
13 border: 1px solid red;
14 }
15 input.ng-valid {
16 border: 1px solid green;
17 }
18 </style>
19 </head>
20 <body>
21 <form name="signup_form"
22 ng-controller="FormController"
23 ng-submit="submitForm()" novalidate>
24 <div ng-repeat="field in fields"
25 ng-form="signup_form_input">
26 <input type="text"
27 name="dynamic_input"
28 ng-required="field.isRequired"
29 ng-model="field.name"
30 placeholder="{{field.placeholder}}" />
31 <div
32 ng-show="signup_form_input.dynamic_input.$dirty &&
33 signup_form_input.dynamic_input.$invalid">
34 <!--内容更改且不合法时显示提示信息-->
35 <span class="error"
36 ng-show="signup_form_input.dynamic_input.$error.required">
37 The field is required.
38 </span>
39 </div>
40 </div>
41 <button type="submit"
42 ng-disabled="signup_form.$invalid">
43 <!--表单不合法时禁用提交按钮-->
44 Submit All
45 </button>
46 </form>
47 <script type="text/javascript">
48 angular.module('myApp',[])
49 .controller('FormController',function($scope) {
50 $scope.fields = [
51 {placeholder: 'Username', isRequired: true},
52 {placeholder: 'Password', isRequired: true},
53 {placeholder: 'Email (optional)', isRequired: false}
54 ];
55 $scope.submitForm = function() {
56 alert("it works!");
57 };
58 });
59 </script>
60 </body>
61 </html>
由于AngularJS中用来取代<form>的ng-form指令可以嵌套,并且外部表单在所有子表单都合 法之前一直处于不合法状态,因此我们可以在动态生成子表单的同时使用表单验证功能。