[英]React/Redux fails when a Select option is selected the first time but not the second
[英]Invalidate select when the first option is selected
我將通過第一個值來驗證選擇框(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
,如果要創建驗證指令,請使用ngModelController.$validators
(而不是$parsers
和$formatters
)。 另外,如果您具有強制性要求,則無需檢查ngModel
是否存在。
代替使用值數組,而使用對象數組,如下所示:
$scope.mainVideoSources = [ { "value": 0, "text": "Please, select a value" }, {{ "value": 0, "text": "Value1"}, { "value": 0, "text": "Value2"} ];
@ hon2a,本機Angular驗證效果很好,謝謝。 我已經在$ validators上重寫了指令。 現在看起來
App.directive('requiredSelect', function () {
return {
restrict: 'AE',
require: 'ngModel',
link: function(scope, element, attributes, ngModel) {
ngModel.$validators.requiredSelect = function(modelValue, viewValue) {
var value = modelValue || viewValue;
var requiredSelect = 'Please, select a value'; //TBD.. select first ngOption
return value != requiredSelect;
};
}
};
});
它對我有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.