<body ng-app="myApp" ng-controller="signUpController">
<form name="signUpForm" ng-submit="submitForm()">
<label>用户名</label>
<pre>合法{{signUpForm.username.$valid}}</pre>
<pre>{{userdata.username}}</pre>
<input name="username"
ng-model="userdata.username"
ng-class="{'error':signUpForm.username.$invalid && signUpForm.username.$dirty}"
type="text"
ng-minlength="4"
ng-maxlength="10"
required />
<p class="error" ng-if="(signUpForm.username.$error.required &&
signUpForm.username.touched">用户名不能为空</p>
<p class="error" ng-if="(signUpForm.username.$error.minlength || signUpForm.username.$error.maxlength) &&
signUpForm.username.touched">用户名长度应在4到10位之间</p>
<label>密码</label>
<pre>合法{{signUpForm.password.$valid}}</pre>
<pre>{{userdata.password}}</pre>
<input name="password"
type="password"
ng-model="userdata.password"
required
ng-minlength="6"
ng-maxlength="255"
required />
<p class="error" ng-if="(signUpForm.username.$error.required &&
signUpForm.username.touched">密码不能为空</p>
<p class="error" ng-if="(signUpForm.password.$error.minlength || signUpForm.password.$error.maxlength) &&
signUpForm.username.touched">用户名长度应在6到255位之间</p>
<label>确认密码</label>
<pre>合法{{signUpForm.password2.$valid}}</pre>
<pre>{{userdata.password2}}</pre>
<input name="password2"
type="password"
ng-model="userdata.password2"
compare="username.password"
required />
<p class="error" ng-if="(signUpForm.password2.$error.compare &&
signUpForm.password2.touched">密码不一致</p>
<button ng-disabled="signUpForm.username.$invalid || signUpForm.password.$invalid">提交</button>
</form>
</body>
angular.module('myApp',[]).controller('signUpController',function($scope){
$scope.userdata={};//所有的表单数据都存在userdata里边
$scope.submitForm=function(){
console.log($scope.userdata);
if($scope.signUpForm.$invalid){
alert("信息有误");
}else{
alert("提交成功");
}
}
})
.directive('compare',function(){
var o={};
o.strict='AE';
o.scope={
orgText:'=compare'
}
o.require='ngModel';
o.link=function(sco,ele,att,con){
con.$validators.compare=function(v){
return v==sco.orgText;
}
sco.$watch('orgText',function(){
con.$validate();
})
}
return o;
})