gpt4 book ai didi

AngularJS:如何根据自定义 bool 值设置有效性

转载 作者:行者123 更新时间:2023-12-05 00:24:17 25 4
gpt4 key购买 nike

我想根据自定义 bool 值设置表单元素的有效性。考虑以下密码字段:

<input type="password" name="password" ng-model="user.password" required>
<input type="password" name="passwordRepeat" ng-model="user.passwordRepeat" required>

如果重复密码与原始密码匹配,我想将第二个输入字段标记为有效。就像是:
<input type="password" name="passwordRepeat" ng-model="user.passwordRepeat" my-validation-check="user.passwordRepeat === user.password" required>

为此,我找不到任何 Angular 指令。有任何想法吗?也许为此创建我自己的指令?不幸的是,我不是 Angular 专家……它应该是这样的:
angular.module('app').directive('myValidationCheck', function() {
return {
scope: true,
require: 'ngModel',
link: function(scope, elm, attrs, ngModel) {
// eval and watch attrs.myValidationCheck
// and use ngModel.$setValidity accordingly
}
};
});

谢谢!

最佳答案

我花了很多时间根据您在下面的答案找到最佳答案(非常感谢!)。对我来说,诀窍很简单:

angular.module('myApp').directive('myValidationCheck', function() {
return {
scope: {
myValidationCheck: '='
},
require: 'ngModel',
link: function(scope, elm, attrs, ngModel) {

scope.$watch('myValidationCheck', function(value) {
ngModel.$setValidity('checkTrue', value ? true : false);
});

}
};
});

为了
<input type="password" name="passwordRepeat" my-validation-check="user.password === user.passwordRepeat" ng-model="user.passwordRepeat" required>

这真的很灵活。您可以在 my-validation-check 中使用任何您想要的东西,例如确保选中复选框或任何更复杂的表达式为真。

希望这不仅对我有帮助.. :-)

关于AngularJS:如何根据自定义 bool 值设置有效性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26547488/

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