1
因爲AngularJS沒有原生的「確認密碼」功能,所以今天我正在編寫我自己的應用程序。我似乎很多教程這樣做在線,和我下面的一個非常受歡迎的一個在用K斯科特·艾倫寫了他Odetocode.com blog自定義AngularJS「確認密碼」指令不起作用
我對它的版本是這樣的:
指令
angular.module('dashboard').directive('pwCheck', function() {
return {
require: 'ngModel',
scope: {
otherModelValue: '=pwCheck'
},
link: function(scope, element, attributes, ngModel) {
ngModel.$validators.pwCheck = function(modelValue) {
return modelValue == scope.otherModelValue;
};
scope.$watch('otherModelValue', function() {
ngModel.$validate();
});
}
};
});
該指令非常明瞭,它監視其他模型值,每次更改時都會檢查兩個值是否相等。當他們最終這樣做時,我的自定義表單驗證「pwCheck」返回true,這應該允許表單提交。當它返回false時,字段下面的錯誤信息將顯示出來,表單將會失效。
HTML
<form-input icon="fa-key fa-fw">
<input type="password" name="password" ng-model="newUser.password"
placeholder="Password" ng-minlength="6" strength required/>
</form-input>
<form-input icon="fa-key fa-fw">
<input type="password" name="confirmPassword"
ng-model="newUser.confirmPassword"
placeholder="Retype Password" required pwcheck="newUser.password" />
</form-input>
<span ng-show="registrationForm.confirmPassword.$dirty">
<span ng-show="registrationForm.confirmPassword.$error.pwCheck">
Confirmation password is required, and must match.
</span>
</span>
據我所知,這應該是工作。我非常仔細地遵循了Scott制定的計劃,而且我沒有看到我的代碼邏輯中存在任何缺陷。我正在使用AngularJS的v1.2.28,也許該版本不支持我正在做的事情。
有人看到有什麼問題嗎?
謝謝! Zach
是的!就是這樣。謝謝。 –
我會盡快接受答案;) –
不用擔心,很高興能成爲幫助:-) – Donal