I have the following code for a select drop down input that is styled in Bootstrap.
you can initial the value of selector in controller:
<select class="form-control" name="businessprocess" ng-model="businessprocess">
<option value="A">-- Select Business Process --</option>
<option value="C">Process C</option>
<option value="Q">Process Q</option>
</select>
in Controller:
$scope.businessprocess = "A" ;
or "C","Q",whatever you want, so the select will always have value. i think you don't need "required" here in select.
If you don't want an init a value. also do some extra effect when user don't select it.
<select class="form-control" name="businessprocess" ng-model="businessprocess" myRequired>
<option value="">-- Select Business Process --</option>
<option value="C">Process C</option>
<option value="Q">Process Q</option>
</select>
then write the directive:
model.directive("myRequired", function() {
return {
restrict: 'AE',
scope: {},
require: 'ngModel',
link: function(scope, iElement, iAttrs) {
if(iElement.val() == ""){
//do something
return;
} else {
//do other things
}
});
}
};
});
Use the following code snippet
<select class="form-control" name="businessprocess" ng-model="businessprocess">
<option value="A" disabled selected hidden>-- Select Business Process --</option>
<option value="C">Process C</option>
<option value="Q">Process Q</option>
</select>
Maybe this code, can be usefull for this... in this case the form is called myform
<select ng-model="selectX" id="selectX" name="selectX" required>
<option value="" ></option>
<option value="0" >0</option>
<option value="1">1</option>
</select>
<span style="color:red" ng-show="myform.selectX.$dirty && myform.selectX.$invalid">
<span ng-show="myform.selectX.$error.required">Is required.</span>
</span>
a best way and straight one is to use:
HTML
<select name="businessprocess" ng-model="businessprocess" required>
<option selected disabled value="">-- Select Business Process --</option>
<option ng-repeat="v in processes" value="{{v.id}}">{{v.value}}</option>
</select>
This works for me. Form is invalid until user selects any other value than "Choose..."
<select name="country" id="country" class="form-control" formControlName="country" required>
<option selected value="">Choose...</option>
<option *ngFor="let country of countries">{{country.country}}</option>
</select>
JS
angular.module('interfaceApp')
.directive('requiredSelect', function () {
return {
restrict: 'AE',
require: 'ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.requiredSelect = true; // force truthy in case we are on non input element
var validator = function(value) {
if (attr.requiredSelect && ctrl.$isEmpty(value)) {
ctrl.$setValidity('requiredSelect', false);
return;
} else {
ctrl.$setValidity('requiredSelect', true);
return value;
}
};
ctrl.$formatters.push(validator);
ctrl.$parsers.unshift(validator);
attr.$observe('requiredSelect', function() {
validator(ctrl.$viewValue);
});
}
};
});