gpt4 book ai didi

javascript - 选择第一个选项时使选择无效

转载 作者:行者123 更新时间:2023-12-03 11:12:32 25 4
gpt4 key购买 nike

我将通过第一个值验证选择框(ngOption)(如果选择第一个值 - false,如果没有 - true),并且我不想在选择框中使用预定义值,如下所示:

<select id="mainVideo" class="form-control"
ng-model="qtTestData.mainVideo"
ng-options="mainVideo for mainVideo in mainVideoSources"
name="mainVideo"
required>
<option value="">-- Please, select a value --</option>
</select>

所以,我有这样的选择框:

<select id="mainVideo" class="form-control" requiredSelect
ng-model="qtTestData.mainVideo"
ng-options="mainVideo for mainVideo in mainVideoSources"
name="mainVideo"
required>
</select>

我的数组是:

 $scope.mainVideoSources = ['Please, select a value', 'Value1', 'Value2'];

我使用此指令来定义是否选择第一个值(这意味着用户没有更改该值)

App.directive('requiredSelect', function () {
return {
restrict: 'AE',
require: 'ngModel',
link: function(scope, element, attributes, ngModel) {
if (!ngModel) return;
attributes.requiredSelect = true;

var validator = function(value) {
if ( value != 'Please, select a value' ) {
ngModel.$setValidity('requiredSelect', false);
return false;
} else {
ngModel.$setValidity('requiredSelect', true);
return true;
}
};
ngModel.$formatters.push(validator);
ngModel.$parsers.unshift(validator);
attributes.$observe('requiredSelect', function() {
validator(ngModel.$viewValue);
});
}
};
});

如果选择了无效值,则应显示 HTML:

<div class="has-error bg-danger" ng-show="qtTestForm.mainVideo.$error.requiredSelect">
<p class="text-center">Oops, something wasn't right</p>
</div>

但是这不起作用...以及如何以 Angular 方式重写语句 (value != 'Please, select a value') ?在JS中就像这样 select.selectedIndex == 0

最佳答案

您可以将数据分为“数据值”和“显示值”:

sources = [{
value: '',
label: 'Please select a value'
}, {
value: 'value1'
}, ...]

然后使用

<select ng-options="item.value as item.label for item in sources" required ...></select>

required验证器完成剩下的工作。无需创建您自己的指令。

<小时/>

作为旁注,如果您要创建验证指令,请使用 ngModelController.$validators (而不是 $parsers$formatters)。此外,如果您将 ngModel 作为强制要求,则无需检查它是否存在。

关于javascript - 选择第一个选项时使选择无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27508823/

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