Jeff Finn Jeff Finn - 10 months ago 47
AngularJS Question

AngularJS Select list has a blank item

I have a few Select lists on my page one of them works fine the rest of them have a blank item at the top of the options list.

This works

<select data-ng-model="c.ResultOptionId" ng-change="checkResult(c)">
<option value="" selected>--Select Option--</option>
<option data-ng-repeat="opt in c.ResultOptions" value="{{opt.Value}}">{{opt.Text}}</option>

This has a extra blank item

<select data-ng-model="c.EquipmentId">
<option value="" selected>--Select Equipment--</option>
<option data-ng-repeat="eq in c.Equipment" value="{{eq.Value}}">{{eq.Text}}</option>

The HTML generated for the select list item is

<select data-ng-model="c.EquipmentId" class="ng-pristine ng-valid ng-not-empty ng-touched">
<option value="? number:0 ?"></option>
<option value="" selected="">--Select Equipment--</option>
<!-- ngRepeat: eq in c.Equipment -->
<option data-ng-repeat="eq in c.Equipment" value="2" class="ng-binding ng-scope">EQ-001</option>
<!-- end ngRepeat: eq in c.Equipment -->

I'm new to AngularJs but from what I've read this should work. I have checked the data returned from my API call and that is correct there are no unexpected items.

Thanks for any help


If you use ng-repeat to generate the options, as the documentation indicates, the bound value is, always, a string.

But the value stored in the ngModel (c.EquipmentId) is a number. So you're telling Angular: here's a list of options with their values, which are strings, and please select, among the string values, the one equal to this number. Since a string is never equal to a number, angular generates an additional option.

So, as usual, use ng-options to generate your options:

<select data-ng-model="c.EquipmentId"
        ng-options="eq.Value as eq.Text for eq in c.Equipment">
    <option value="">--Select Equipment--</option>

And make sure that c.EquipmentId contains one of the proposed equipment values, or is null or undefined.