刚开始学习AngularJs,尝试写表单验证,自己自定义一个验证确认密码的指令怎么不起作用?
代码如下:
angular.module('myApp',[])
.controller('SignUpController',function($scope){
$scope.userdata = {};
$scope.submitForm = function() {
console.log($scope.userdata);
if($scope.signUpForm.$invalid){
alert("请填写完信息");
}else {
alert("注册成功");
}
};
})
.directive('confirm-pwd',function(){
console.log($scope.userdata.password1);
return {
require:'ngModel',
restrict:'AE',//匹配模式 A属性
scope:{orgTxt: '=confirmPwd'},
link: function(sco,ele,att,con) {
con.validators.confirmPwd = function(v) {
return v === sco.orgTxt;
};
sco.watch('orgTxt',function() {
con.validate();
});
}
};
});
html部分代码如下:
<form name="signUpForm" ng-submit="submitForm()" novalidate>
<div class="form-group">
<label>名称</label>
<input type="text"
class="form-control"
autofocus="autofocus"
name = "username"
ng-model = "userdata.username"
ng-minlength = "2"
ng-maxlength = "6"
ng-required
id="name1">
<p ng-if="(signUpForm.username.$error.minlength ||
signUpForm.username.$error.maxlength)&& signUpForm.username.$dirty">
用户名长度应在2到4个字符之间</p>
</div>
<div class="form-group">
<label>密码</label>
<input type="password"
class="form-control"
name="password"
ng-model="userdata.password"
ng-minlength="4"
ng-maxlength="12"
ng-required>
<p ng-if="(signUpForm.password.$error.minlength||
signUpForm.passsword.$error.maxlength)&&
signUpForm.password.$dirty">
密码长度应该在4-12位之间</p>
</div>
<div class="form-group">
<pre>合法:{{signUpForm.password1.$invalid}}</pre>
<pre>{{userdata.password1}}</pre>
<label>确认密码</label>
<input type="password"
class="form-control"
name="password1"
ng-model="userdata.password1"
confirmPwd="userdata.password"
ng-required>
<p ng-if="signUpForm.password1.$error.confirmPwd &&
signUpForm.password1.$dirty">两次输入密码不一致</p>
</div>
<button type="submit" class="btn" id="valite">验证</button>
</form>
1.把$加上
2..
directive('confirmPwd'....
定义用驼峰,调用用连字符confirm-pwd="userdata.password"
3.不知道
ng-app
和ng-controller
加了没 因为没贴。最后合法的逻辑好像有点问题。密码不一致合法会提示
true
,一致提示false
,其他功能正常。