2017-06-12 35 views
0

我正在與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

謝謝你的幫助!

+0

上面的plunker和小提琴代碼有很多不同之處。只要確保沒有分歧 –

回答