0

我試圖顯示消息時,密碼不匹配,但不是不顯示任何想法?我試圖顯示消息時密碼不匹配,但不是不顯示任何想法?Angularjs:顯示消息

指令:

angular.module('crud') 
    .directive('equal', function() { 
    return { 
     require: 'ngModel', 
     scope: { 
     equal: '=' 
     }, 
     link: function(scope, elem, attrs, ctrl) { 

     ctrl.$validators.equal = function(modelValue, viewValue) { 
      return modelValue === scope.equal; 
     }; 

     scope.$watch('equal', function(newVal, oldVal) { 
      ctrl.$validate(); 
     }); 
     } 
    }; 
    }); 

HTML

<form name="userForm" ng-submit="signup()" class="form-horizontal" role="form" > 
    <input type="password" class="form-control ng-invalid submitted" id="password" name="password" ng-model="password" ng-minlength="8" ng-maxlength="20" required /> 

    <input type="password" equal="password" class="form-control ng-invalid submitted" id="confirmPassword" name="confirmPassword" ng-model="confirmPassword" required /> 

    <span ng-show="userForm.password.$error.equal && userForm.password.$dirty">Passwords don't match.</span> 
</form> 

回答

0

一切都很好,但有一個例外,你應該在密碼輸入添加相同的指令,因爲你是顯示密碼錯誤,所以你應該驗證密碼。除此之外,沒關係。儘管你可能會考慮使用ng-messages來顯示錯誤。

angular.module('crud', ['ngMessages']); 
 

 
angular.module('crud') 
 
    .directive('equal', function() { 
 
    return { 
 
     require: 'ngModel', 
 
     scope: { 
 
     equal: '=' 
 
     }, 
 
     link: function(scope, elem, attrs, ctrl) { 
 
     ctrl.$validators.equal = function(modelValue, viewValue) { 
 
      return modelValue === scope.equal; 
 
     }; 
 

 
     scope.$watch('equal', function(newVal, oldVal) { 
 
      ctrl.$validate(); 
 
     }); 
 
     } 
 
    }; 
 
    });
.valid { 
 
    border: 1px solid green; 
 
} 
 

 
.invalid { 
 
    border: 1px solid red; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script> 
 
<script src="https://code.angularjs.org/1.5.5/angular-messages.js"></script> 
 
<div ng-app="crud"> 
 
<form name="userForm" class="form-horizontal" role="form" > 
 
    <input type="password" class="form-control ng-invalid submitted" id="password" name="password" equal="confirmPassword" ng-model="password" ng-minlength="8" ng-maxlength="20" ng-class="{'valid': userForm.password.$valid || !userForm.password.$dirty, 'invalid': userForm.password.$invalid && userForm.password.$dirty}" required /> 
 

 
    <input type="password" class="form-control submitted" id="confirmPassword" name="confirmPassword" ng-model="confirmPassword" required /> 
 

 
    <div ng-messages="userForm.password.$error" ng-show="userForm.password.$dirty" role="alert"> 
 
     <div ng-message="required">Please enter a value for this field.</div> 
 
     <div ng-message="equal">Passwords don't match.</div> 
 
    </div> 
 
    
 
</form> 
 
</div>

+0

ü可以用NG的消息放好嗎? – nevergiveup

+0

@nevergiveup當然,我更新了上面的代碼片段,以便它使用ng-messages – sielakos

+0

當邊界不正確並且邊界格林函數相關時,如何將邊界置於紅色? – nevergiveup