0

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?

Miles Peterson
  • 265
  • 1
  • 4
  • 12

2 Answers2

1

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

Community
  • 1
  • 1
Vineet
  • 4,525
  • 3
  • 23
  • 42
0

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;

kira_codes
  • 1,457
  • 13
  • 38
  • By values in the option, do you mean the option's value attribute, or the html within the option tag? – Miles Peterson Jul 08 '15 at 19:30
  • The options's value attribute. To me it seems like your MyCtrl.value is not in [1,2,3], so Angular tries to set the selected value to a nonexistant one, resulting in the generation of a blank select option. – kira_codes Jul 08 '15 at 19:35