我目前有一個角度指令驗證密碼並確認密碼字段爲匹配。它工作到一定程度,它在密碼不匹配時會引發錯誤。但是,它不會拋出錯誤,直到您在兩個字段中輸入數據。我該如何做到這一點,因爲一旦你在一個領域或另一個領域輸入數據,就會拋出不匹配密碼的錯誤。驗證密碼和確認密碼字段每當一個或其他字段模型更改(每個按鍵)與角度指令
這裏是指令(它被添加到需要符合這兩個領域):
.directive('passwordVerify', function() {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, elem, attrs, ngModel) {
//if (!ngModel) return; // do nothing if no ng-model
// watch own value and re-validate on change
scope.$watch(attrs.ngModel, function() {
validate();
});
// observe the other value and re-validate on change
attrs.$observe('passwordVerify', function(val) {
validate();
});
var validate = function() {
// values
var val1 = ngModel.$viewValue;
var val2 = attrs.passwordVerify;
// set validity
ngModel.$setValidity('passwordVerify', !val1 || !val2 || val1 === val2);
};
}
};
});
這裏是我的表格的指令:
<div class="small-5 columns">
<div class="small-12 columns">
<label>Password
<input ng-class="{ notvalid: submitted && add_user_form.user_password.$invalid }" class="instructor-input" id="user_password" type="password" name='user_password' placeholder="password" value='' required ng-model="user.user_password" password-verify="[[user.confirm_password]]">
</label>
<p class="help-text"><span class=" ">Required</span></p>
<div class="help-block" ng-messages="add_user_form.user_password.$error" ng-show="add_user_form.user_password.$touched || add_user_form.user_password.$dirty">
<span class="red"><div ng-messages-include="/app/views/messages.html" ></div></span>
</div>
</div>
<div class="small-12 columns">
<label>Confirm Password
<input ng-class="{ notvalid: submitted && add_user_form.confirm_password.$invalid }" class="instructor-input" id="confirm_password" ng-model="user.confirm_password" name="confirm_password" type="password" placeholder="confirm password" name="user_confirm_passsword" required password-verify="[[user.user_password]]">
</label>
<p class="help-text"><span class=" ">Enter matching password</span></p>
<div class="help-block" ng-messages="add_user_form.confirm_password.$error" ng-show="add_user_form.confirm_password.$dirty || add_user_form.confirm_password.$touched ">
<span class="red"><div ng-messages-include="/app/views/messages.html" ></div></span>
</div>
</div>
</div>
你需要這樣調用密碼驗證=「[[user.confirm_password]]」,只是好奇,因爲我之前沒有在屬性調用中看到[[]]? – vodich
是的,如果你不這樣做,它會假髮。我從別人那裏得到了這個指令,它有點搖搖欲墜。我認爲它正在驗證屬性中的數據而不是模型,這就是爲什麼它在[[]]中的原因,順便說一句,我是用{{}}替代的,因爲我使用的是句柄模板。因此,他編碼的方式是直接將模型中的數據輸入到屬性中,而不是直接比較模型中的數據。有關我如何改變這種情況的任何想法?我是新來的角,通常使用PHP做所有的MVC服務器端。 – OGZCoder
嗯,你不能通過指令中的第二個輸入字段模型,並與更改時的當前輸入字段模型進行比較?如果您將代碼放在js-bin或jsFiddle上,我可能會幫助 – vodich