首页 > 代码库 > angularjs 表单验证ngMessages和创建自定义指令结合

angularjs 表单验证ngMessages和创建自定义指令结合

index.html

 1 <!doctype html>
 2 <html >
 3 <head>
 4     <meta charset="utf-8">
 5 </head>
 6 <style>
 7     /*input.ng-invalid {
 8         border: 1px solid red;
 9     }
10     input.ng-valid {
11         border: 1px solid green;
12     }*/
13 </style>
14 <script src=http://www.mamicode.com/"js/angular.js"></script>
15 <script src=http://www.mamicode.com/"js/clock.js"></script>
16 <script src=http://www.mamicode.com/"js/angular-messages.js"></script>
17 <script src=http://www.mamicode.com/"js/angular-messages.min.js"></script>
18 <body ng-app="myApp">
19 <form name="form1" novalidate ng-submit="signupForm()" ng-controller="signupController">
20     <label>Your name</label>
21     <input type="text" placeholder="Name" ng-model="name" name="name" ng-minlength="3"
22            ng-maxlength="20" required >
23     <div class="error" ng-messages="form1.name.$error" >
24         <my-error></my-error>
25 </div> 26 <button type="submit">Submit</button> 27 </form> 28 </body> 29 </html>

clock.js

1 var app=angular.module(myApp,[ngMessages]);
2 app.directive(myError,function(){
3           return{
4               restrict:‘EAC,
5 template:<div ng-message="required">请输入用户名 </div> <div ng-message="minlength">少于3位</div> <div ng-message="maxlength">多余20位</div> 6 } 7 })

 E代表元素  A代表属性  C代表类 M代表注释

<my-error></my-error>  可以换成<div my-error></div>

angularjs 表单验证ngMessages和创建自定义指令结合