I need to pre-fill a <select>
element with some options from the scope and would like the one whos value is bound as the model to be selected initially.
The problem is that the model value is not being selected and a blank element is created and selected instead.
JSON Model
var fruits = {
"0":"apple",
"1":"pear",
"2":"banana"
}
Controller
$scope.items = fruits;
$scope.myfruit = 1; // also tried "1"
Template Markup:
<select class='form-control' name="fruit"
ng-model="myfruit"
ng-options="key as val for (key, val) in items" >
</select>
The dropdown menu renders with all values present and updates the model with the keys (as intended), but the first element is an empty item that is selected.
However, once an option is chosen, the empty option disappears.
I also tried writing the markup using ng-repeat
with identical results:
<select class='form-control' name="fruit"
ng-model="myfruit" >
<option ng-repeat="(k, val) in items" value="{{k}}">{{val}}</option>
</select>
How can I get the value represented in the model to be selected when initialized?
$scope.myfruit = '1'
– Avnesh Shakya