Strange binding / validation behavior when binding picklist to boolean

Can someone explain to me the following weird binding / checking behavior when binding a select list to boolean values?

Choosing Yes (true) works as expected. The choice of No (false) is obviously not fulfilled:

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 the drop-down list. The values ​​of the option elements must be true or false (logical, not string).

Thank you for your help!

+4
source share
1 answer

It seems that the required directive does not consider false valid and sets the value of your model 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 a few options:

  • Use ngRequired instead of required . This allows you to select the custom expression you want, for example: ng-required="!(myModel == true || myModel == false)" . Here is an example script .
  • You can create your own modified directive required , which allows false
  • Bind to something else (1 and 0 or "true" and "false", as you mentioned)

Also note that you can add an empty parameter value so that the first element does not say β€œYes” after selecting it:

 <select name="parameter" ng-model="myModel" ng-options="x.value as x.label for x in trueFalseOptions"> <option value=""></option> </select> 
+6
source

Source: https://habr.com/ru/post/1489713/


All Articles