Strange binding/validation behaviour when binding select list to booleans
angularjs
Solution
It looks like the `required` directive does not consider a value of `false` to be valid and sets your model value to `undefined`:
Github source link:
var validator = function(value) {
if (attr.required && (isEmpty(value) || value === false)) {
ctrl.$setValidity('required', false);
return;
} else {
ctrl.$setValidity('required', true);
return value;
}
};
Here are some options:
- Use `ngRequired` instead of `required`. This lets you choose a custom required expression like: `ng-required="!(myModel == true || myModel == false)"`. Here is a fiddle with an example.
- You can create your own modified `required` directive that will allow false
- Bind to something else (1 and 0 or "true" and "false" like you mentioned)
Also note you may want to add an empty option value so the first item doesn't say "Yes" after you select it:
<select name="parameter" ng-model="myModel" ng-options="x.value as x.label for x in trueFalseOptions">
<option value=""></option>
</select>
Problem
Can anybody explain me the following strange binding/validation behaviour when binding a select list to boolean values? Selecting "Yes" (true) works as expected. Selecting "No" (false) obviously does not: JSFIDDLE: http://jsfiddle.net/mhu23/ATRQG/14/ ``` $scope.trueFalseOptions = [{ value: true, label: 'Yes' }, { value: false, label: 'No' }]; <select name="parameter" required ng-model="myModel" ng-options="x.value as x.label for x in trueFalseOptions"></select> ``` Am I doing something wrong? I would like to be able to select "Yes" or "No" from a dropdown list. The values of the option items should be true or false (boolean, not string). Thanks for your help!