简体   繁体   中英

Angular required select option not working for placeholder

plunkr here

I have a default select value properly not fulfilling the required validation:

<form name="testForm" novalidate>
  <select ng-model="model.selecter" required ng-options="opt for opt in options">
    <option value="">Select One</option>
  </select>
</form>

$scope.options = [
    'First',
    'Second',
    'Third'
];

While "Select One" is selected, testForm.$valid is false , as it should be.

However, I would like to be able to add my placeholder to the options array as well, but in this instance it marks it as valid.

<form name="testForm" novalidate>
  <select ng-model="model.selecter" required ng-options="opt for opt in options">
  </select>
</form>

$scope.options = [
    'Select One',
    'First',
    'Second',
    'Third'
];

$scope.model = { selecter: $scope.options[0] }; // sets the default selected option

Here testForm.$valid is always true . Is there any way to make my Select One option not fulfill the required status of the form?

Not sure why you are trying to complicate something that works, but if you must you will have to make some other changes as well. Change your select to be like this

             <select ng-model="model2.selecter" required ng-options="opt.value as opt.label for opt in options2">
             </select>

And your values to be like this

      $scope.options2 = [
        {label:'Select One',value:''},
        {label:'First',value:'1'}
      ];

And do not give your model variable a value. Make it blank.

         $scope.model2 = { 
            selecter: ''
        };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM