gpt4 book ai didi

javascript - 如何将 setValidity 应用于元素?

转载 作者:行者123 更新时间:2023-11-28 01:19:19 31 4
gpt4 key购买 nike

我有指令验证用户输入的相同密码。但在指令内部我想为两个输入元素setValidity = true

.directive('equalsTo', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
scope.$watch(attrs.ngModel, function() {
console.log(ctrl.$viewValue);
debugger;
if ($('#' + attrs.id).val() === $(attrs.equalsTo).val()) {
ctrl.$setValidity('equalsTo', true);
//here I want to apply $(attrs.equalsTo).setValidity('equalsTo', true);
} else {
ctrl.$setValidity('equalsTo', false);
//here I want to apply $(attrs.equalsTo).setValidity('equalsTo', false);
}
});
}
};
});

我想在 $(attrs.equalsTo) 这样的元素上应用 setValidity

<input id="newPassword" name="newPassword" ng-model="newPassword" type="password"
class="form-control" placeholder="new password" ng-minlength="5" equals-to="#verifyNewPassword">
<input id="verifyNewPassword" name="verifyNewPassword" ng-model="verifyNewPassword" type="password"
class="form-control" placeholder="verify new password" equals-to="#newPassword">

最佳答案

有一个更好的方法可以做到这一点,传入依赖输入的ngModelController。所以html就变成了

<input id="newPassword" name="newPassword" ng-model="newPassword" type="password"
class="form-control" placeholder="new password" ng-minlength="5" equals-to="form.verifyNewPassword">
<input id="verifyNewPassword" name="verifyNewPassword" ng-model="verifyNewPassword" type="password"
class="form-control" placeholder="verify new password" equals-to="form.newPassword">

这里我假设表单的名称是

<form name='form'>

将其替换为您的表单的名称。

然后更改指令定义以从其他 ngModelController 读取数据。

.directive('equalsTo', function() {
return {
require: 'ngModel',
link: function(scope, elm, attrs, ctrl) {
scope.$watch(attrs.ngModel, function() {
console.log(ctrl.$viewValue);
var otherController=scope.$eval(attrs.equalsTo);
if (ctrl.$viewValue===otherController.$viewValue) {
ctrl.$setValidity('equalsTo', true);
otherController.setValidity('equalsTo', true);
} else {
ctrl.$setValidity('equalsTo', false);
//here I want to apply
otherController.setValidity('equalsTo', false);
}
});
}
};
});

关于javascript - 如何将 setValidity 应用于元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23422264/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com