gpt4 book ai didi

javascript - AngularJS 摘要循环错误,ngmodel 在自定义验证中被删除

转载 作者:行者123 更新时间:2023-12-03 10:46:02 24 4
gpt4 key购买 nike

作为 AngularJS 的新手,我在为下拉选择编写自定义验证时遇到了一个非常奇怪的错误。

正如您所料,我用

编写了此下拉列表
<select name="somename" id="someid" ng-model="foo" ng-model-options="{allowInvalid: true}"  validate-input>
<option></option>
<option></option>
</select>

在本例中,validate-input 是我的自定义指令。是这样写的:

directives.directive("validateInput", function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, ele, attrs, ctrl) {
ctrl.$validators.isAcceptable = function (value) {

var status = false;

if (value === '0') {
status = true;
}

return status;

};
}
}
});

在本例中,isAcceptable 是我正在创建的标志。

无论如何,针对实际问题本身。每当我启动应用程序时,我都会发现 ng-model 的实际值被“删除”。也就是说,它要么是未知的,要么是 NaN(当然取决于输入)。为了解决这个问题,我在选择标签中添加了以下指令: ng-model-options="{allowInvalid: true}然而,这并没有解决我的问题。

这个问题如此重要的原因是,当 ng-model 被错误验证(设置为 NaN 或未知)删除时,这会导致我的应用程序稍后出现严重错误。我能想到的唯一解决方案是使 ng-model="0"或 =""(这是一个错误的验证)并保留这些值,而不是从应用程序中删除模型本身。

最佳答案

尝试这样的事情:

directives.directive("validateInput", function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, ele, attrs, ctrl) {
ctrl.$validators.isAcceptable = function (modelValue, viewValue) {
var value = modelValue || viewValue;
return value === '0' ? true : false;
};
}
}
});

modelValue 仅在 viewValue 满足验证条件后设置。因此在初始化时它是空白的,另一个验证器可能会阻止它设置值。

您可能完全想使用这种格式:

directives.directive("validateInput", function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, ele, attrs, ctrl) {
var setValidator = function (value) {
var isValidFormat = function () {
return $value === '0' ? true : false;
};
ctrl.$setValidity('isAcceptable', isValidFormat);
return value;
};
ctrl.$parsers.unshift(setValidator);
ctrl.$formatters.unshift(setValidator);
}
}
});

关于javascript - AngularJS 摘要循环错误,ngmodel 在自定义验证中被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28569632/

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