角度比较密码指令

use*_*830 1 angularjs

我有这个有密码字段和confirmPassword字段的表单.我想将密码字段与confirmPassword字段进行比较.我这样做有点问题,因为我有一个ng-show,当密码不匹配但是消息总是显示时,应该只显示"Passwords Do Not Match"错误.

    <label class="control-label">Password *
  <div class="row m-b-15">
    <div class="col-md-12">
      <input type="text" placeholder="Password" name="password" required="" ng-model="user.password" class="form-control"/>
    </div>
  </div>
  <label class="control-label">Re-enter Password *</label>
  <div class="row m-b-15">
    <div class="col-md-12">
      <input type="text" placeholder="Re-enter Password" name="confirmPassword" required="" ng-model="user.confirmPassword" ka-compare-to="user.password" class="form-control"/>
      <div ng-show="signUpForm.confirmPassword.$error" class="form-group has-error">
        <label class="control-label">Passwords Do Not Match</label>
      </div>
    </div>
  </div>
</label>

.directive('kaCompareTo', function(){

    return {
        restrict: 'A',
        require: 'ngModel',
        scope: {
            otherModelValue: '=kaCompareTo'
        },
        link: function(scope, element, attributes, ngModel){

            ngModel.$validators.kaCompareTo = function(modelValue){

                return modelValue === scope.otherModelValue;
            };

            scope.$watch("otherModelValue", function() {

                ngModel.$validate();
            });

        }

    }

})
Run Code Online (Sandbox Code Playgroud)

提前致谢.

小智 6

要使其工作,您应该将ng-show条件从更改signUpForm.confirmPassword.$errorsignUpForm.confirmPassword.$error.kaCompareTo

要实现相同的行为,可以使用AngularJS"ng-pattern"属性,而不是创建自定义指令.恕我直言,这是更好的解决方案,因为只有当"confirmPassword"不为空时它才会返回错误:

<input 
type="text" 
placeholder="Re-enter Password" 
name="confirmPassword" 
required="" 
ng-pattern="user.password" 
ng-model="user.confirmPassword" 
class="form-control"/>
<div 
ng-show="signUpForm.confirmPassword.$error.pattern" 
class="form-group has-error">
    <label class="control-label">Passwords Do Not Match</label>
</div>
Run Code Online (Sandbox Code Playgroud)