【发布时间】:2017-07-05 16:08:56
【问题描述】:
我正在尝试构建一个自定义指令(基于我看到的示例)以确保确认密码正确。 我在使用 $setValidity 标记时遇到了一些问题,尽管我的所有 console.log() 都执行并打印出来,但似乎没有更新有效性。即使我在控制台中读取“设置为假”,通过仍保持为真。 我确保名称和 ng-model 是相同的,并且我也尝试使用 scope.$apply,但这会出现一个错误,说我正在尝试应用其他内容。
这是我的代码: HTML
<form ng-submit="signup()" name="profileForm">
<div class="form-group">
<label class="form-label" for="input-example-2">Password</label>
<input class="form-input" ng-model="pnew" type="password" name="pnew" placeholder="Password" required>
</div>
<div class="form-group">
<label class="form-label" for="input-example-2">Confirm Password</label>
<input class="form-input" name="confirm" ng-model="confirm" type="password" placeholder="Password" required pwcheck>
</div>
{{profileForm.confrim.$error.pass}}
<hr>
{{profileForm.confirm.$error}}
<hr>
{{profileForm.confirm.$valid}}
<span ng-show="profileForm.confirm.$error.pwCheck"> the passwords dont match</span>
<div class="form-group">
<button class="btn btn-primary">Sign up</button>
</div>
</form>
pwcheck 指令的 JS 代码
.directive('pwcheck', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
function valid(value){
scope.$watch("confirm", function(newval, oldval){
console.log(value);
console.log(scope.pnew);
if(value==scope.pnew){
console.log("success!");
ctrl.$setValidity('pass', true);
return value;
}
else {
console.log("set to false");
ctrl.$setValidity('pass', false);
return undefined;
}
});
}
ctrl.$parsers.push(valid);
} } });
【问题讨论】:
标签: javascript angularjs validation