我正在与AngularJS合作,我想做一个密码确认字段来检查两个条目是否匹配。为了做到这一点,我使用了本教程中的自定义指令:http://odetocode.com/blogs/scott/archive/2014/10/13/confirm-password-validation-in-angularjs.aspx。自定义密码验证指令不适用
出于某种原因,匹配检查不会给出任何结果。当我输入不同的密码时,它仍然将这些字段视为有效。我想我在AngularJS中错过了自定义指令的用法,但它有点令人困惑,因为我正在采用与本教程中完全相同的代码。
我也在这里检查了相关的问题,但没有运气。
HTML:
<div ng-app="myApp">
<h1>Register!</h1>
<form name="registrationForm" novalidate>
<div class="form-group">
<label>User Name</label>
<input type="text" name="username" class="form-control" ng-model="registration.user.username" required />
<p ng-show="registrationForm.username.$error.required">Required<br/><br/></p>
</div>
<div class="form-group">
<label>Password</label>
<input type="password" name="password" class="form-control" ng-model="registration.user.password" required />
<p ng-show="registrationForm.password.$error.required">Required<br/><br/></p>
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" name="confirmPassword" class="form-control" ng-model="registration.user.confirmPassword" required compare-to="registration.user.password" />
<p ng-show="registrationForm.confirmPassword.$error.required">Required<br/><br/></p>
<p ng-show="registrationForm.confirmPassword.$error.compareTo">Passwords must match !</p>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Register!</button>
</div>
</form>
</div>
JS:
angular.module('myApp', [])
.directive('compareTo', function(){
return {
require: "ngModel",
scope: {
otherModelValue: "=compareTo"
},
link: function(scope, element, attributes, ngModel) {
ngModel.$validators.compareTo = function(modelValue) {
return modelValue == scope.otherModelValue;
};
scope.$watch("otherModelValue", function() {
ngModel.$validate();
});
}
};
})
的jsfiddle显示问题:http://jsfiddle.net/ptb01eak/
工作从教程Plunkr:http://plnkr.co/edit/FipgiTUaaymm5Mk6HIfn?p=preview
谢谢你的帮助!
上面的plunker和小提琴代码有很多不同之处。只要确保没有分歧 –