gpt4 book ai didi

javascript - 自定义验证作为 Angular 中的函数

转载 作者:行者123 更新时间:2023-11-27 22:56:35 25 4
gpt4 key购买 nike

在 Angular 中,我试图验证模糊字段的值。我有一个客户列表,我想检查该字段中的模型值是否在我的客户列表中。如果不是,我想将有效性设置为 false。

我知道 ng-model-options="{updateOn: 'blur'} 存在,但是,我无法使用它,因为该字段是预先输入的,因此它必须根据模型。验证是模糊时需要发生的事情。

答案似乎是:

  1. 将其编写为 Controller 中的函数,并像在指令中一样使用 $setValidity 。使用 ng-blur 触发输入字段中的函数。

    -但是,我不断遇到示例,其中自定义验证(如果模型值与列表中的值不匹配,则使字段无效)仅编写为指令。是否有将自定义验证编写为函数的示例?

  2. 编写一个仅在模糊时触发的指令。

但是,我找不到执行这些操作的示例。

有人有一个将自定义验证作为函数或指令仅在字段模糊时更新的示例吗?

我发现此链接对于自定义验证非常有帮助,但我仍然对函数和指令之间的差异有同样的问题:How to add custom validation to an AngularJS form?

** 我的 typeahead 有效,我不需要帮助让 uib-typeahead 正常工作,而是需要附带的自定义验证

最佳答案

这里是模糊触发的自定义验证的示例:

angular.module('myApp', [])
.directive('customValidation', function() {
return {
require: 'ngModel',
link: function(scope, el, attrs, ngModel) {
el.bind('blur', function(event) {
scope.$apply(function() {
ngModel.$setValidity('customValidation', scope.name == 'test');
});
})
}
};
});

Plunk

关于javascript - 自定义验证作为 Angular 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37557167/

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