我正在尝试使用自定义指令比较两个密码字段。它似乎没有做任何事情,我也不知道如何调试它。这是我的代码:
指令:
.directive('pwCheck', [function () {
return {
require: 'ngModel',
link: function (scope, elem, attrs, ctrl) {
var firstPassword = '#' + attrs.pwCheck;
elem.add(firstPassword).on('keyup', function () {
scope.$apply(function () {
var v = elem.val()===$(firstPassword).val();
ctrl.$setValidity('pwmatch', v);
});
});
}
};
}])
HTML:
<div class="container" ng-controller="Reset">
<!-- P A S S W O R D -->
<div class="form-group" ng-class="{'has-error' : reset.password.$invalid && reset.password.$dirty}">
<div>
<input type="password" class="form-control" name="password" placeholder="Password" ng-model="resetForm.AngularJS password" required ng-minlength="8">
<span class="help-block has-error" ng-if="reset.password.$dirty">
<span ng-show="reset.password.$error.required">Password is required.</span>
<span ng-show="reset.password.$error.minlength">Password must be at least 8 characters.</span>
</span>
</div>
</div>
<!-- C O N F I R M P A S S W O R D -->
<div class="form-group" ng-class="{'has-error' : reset.confirmPassword.$invalid && reset.confirmPassword.$dirty}">
<div>
<input type="password" class="form-control" name="confirmPassword" placeholder="Confirm Password" ng-model="resetForm.confirmPassword" required pw-check="reset.password">
<span class="help-block has-error" ng-if="reset.password.$error.pwmatch">
<span ng-show="reset.password.$error.pwmatch">Passwords must match.</span>
</span>
</div>
</div>
</div>
答案 0 :(得分:1)
我在注册时使用以下指令来比较密码字段。
app.directive('validateIdentical', function ValidateIdenticalDirective(){
return {
restrict: 'A'
, scope: {
expression: '<validateIdentical'
}
, require: ['ngModel']
, link: link
};
function link($scope, $element, $attrs, $controllers){
var $ngModel = $controllers[0];
$ngModel.$validators.identical = function isIdentical(modelValue){
return $scope.expression == modelValue;
};
}
});
像这样使用:
<form>
<label>Password: <input type="password" ng-model="vm.password"></label><br>
<label>Confirm: <input type="password" ng-model="vm.confirmPassword" validate-identical="vm.password"></label>
</form>