角度比较密码指令

时间:2016-01-24 20:55:00

标签: angularjs

我有这个表格,其中包含密码字段和confirmPassword字段。我想将密码字段与confirmPassword字段进行比较。我这样做有一点问题,因为我有一个ng-show,当密码不匹配时,只显示“密码不匹配”错误,但此时消息总是显示。

    <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();
            });

        }

    }

})

提前致谢。

1 个答案:

答案 0 :(得分:6)

要使其有效,您应该将ng-show条件从signUpForm.confirmPassword.$error更改为signUpForm.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>