jek*_*ija 0 angularjs angularjs-directive angular-directive
尝试在angular js中使用自定义指令匹配密码。尽管我看过几个Google教程,但我无法正常工作。我已经创建了一个Plunker,它显示了它在plunker上不起作用。
HTML:
<div class="form-group" ng-class="{ 'has-error': form.password.$invalid && !form.username.$pristine }">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control" ng-model="user.password" required ng-minlength="6" ng-maxlength="12"/>
</div>
<div class="form-group" ng-class="{ 'has-error': form.confirm-password.$invalid && !form.confirm-password.$pristine }">
<label for="confirm-password">Confirm Password</label>
<input type="password" name="confirm-password" id="confirm-password" class="form-control" ng-model="user.confirmpwd" required equal="{{user.password}}"/>
<span ng-show="user.confirmpwd.$error.equal" class="help-block">Password does not match above</span>
</div>
Run Code Online (Sandbox Code Playgroud)
JAVASCRIPT:
app.directive('equal', [
function() {
var link = function($scope, $element, $attrs, ctrl) {
var validate = function(viewValue) {
var comparisonModel = $attrs.equal;
console.log(viewValue + ':' + comparisonModel);
if(!viewValue || !comparisonModel){
// It's valid because we have nothing to compare against
ctrl.$setValidity('equal', true);
}
// It's valid if model is lower than the model we're comparing against
ctrl.$setValidity('equal', viewValue === comparisonModel );
return viewValue;
};
ctrl.$parsers.unshift(validate);
ctrl.$formatters.push(validate);
$attrs.$observe('equal', function(comparisonModel){
return validate(ctrl.$viewValue);
});
};
return {
require: 'ngModel',
link: link
};
}]);
Run Code Online (Sandbox Code Playgroud)
问题似乎在custom指令周围,似乎没有正确绑定到ngModel项?我觉得我必须缺少一些简单的东西,我才刚刚开始学习AngularJS。
密码字段绑定应该起作用,但是您正在验证密码字段至少应包含6个字符长,这意味着只有输入6个或更多字符后,才将其绑定到模型。在此之前,它将是undefined,这就是您在console.log我假设的语句中所得到的。
但是还有其他问题。由于您的字段名称为,因此不会显示错误消息confirm-password。您应该命名它confirmPassword或不带破折号的东西。Angular将该名称用作对象属性,并且JavaScript对象键不能包含破折号。
因此,表单的密码确认部分应如下所示:
<div class="form-group" ng-class="{ 'has-error': form.confirmPassword.$invalid && !form.confirmPassword.$pristine }">
<label for="confirm-password">Confirm Password</label>
<input type="password" name="confirmPassword" id="confirm-password" class="form-control" ng-model="user.confirmpwd" required equal="{{user.password}}"/>
<span ng-show="form.confirmPassword.$error.equal" class="help-block">Password does not match above</span>
</div>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3990 次 |
| 最近记录: |