【发布时间】:2015-02-15 00:16:45
【问题描述】:
我将通过第一个值验证选择框 (ngOption)(如果选择第一个值 - 假,如果不是 - 真),我不想在选择框中使用预定义的值,如下所示:
<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>
但它不起作用......
声明 (value != 'Please, select a value') 如何以 Angular 方式重写?在 JS 中
就像这样 select.selectedIndex == 0
【问题讨论】:
标签: javascript angularjs select angularjs-directive ng-options