Miles Peterson
Miles Peterson

Reputation: 265

Getting rid of the blank item in select tag

So I have the following code:

<select id="basicInput" ng-model="MyCtrl.value">
    <option value=""></option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

But in the console, I find this:

<select id="basicInput" ng-model="MyCtrl.value">
    <option value="? object:null ?"></option>
    <option value=""></option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

I've seen this question resolved before, but all of answers I found were wrestling with either ng-options or ng-repeat. This code uses neither, so why am I getting this issue in the first place? More importantly, how do I prevent my page from loading this tag with the phantom option? Does it have something to do with the ng-model?

EDIT:

Since asking this question, I've added the following to my code:

<select id="basicInput" ng-model="MyCtrl.value">
    <option value="0"></option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

I have also set Myctrl.value = 0. Still I find myself with the same error. Ideas?

Upvotes: 0

Views: 70

Answers (2)

Vineet
Vineet

Reputation: 4635

This question has already answered before. Please check this URL. According them

The empty option is generated when a value referenced by ng-model doesn't exist in a set of options passed to ng-options. This happens to prevent accidental model selection: AngularJS can see that the initial model is either undefined or not in the set of options and don't want to decide model value on its own.

Instead you can do it in this way

<select id="basicInput" ng-model="MyCtrl.value">
  <option value="" ng-if="false"></option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

In short: the empty option means that no valid model is selected (by valid I mean: from the set of options). You need to select a valid model value to get rid of this empty option

Upvotes: 1

kira_codes
kira_codes

Reputation: 1606

You must initialize MyCtrl.value to one of the values provided by the options, otherwise Angular will render an empty selection because the selected model does not exist in the list of options.

in MyCtrl:

$scope.value = 1;

Upvotes: 0

Related Questions