0
votes

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?

1
It's working for me: $scope.myfruit = '1'Avnesh Shakya
ah yes. that worked. I guess I'll have to convert my model to a stringyevg

1 Answers

1
votes

your option value is a string

this should work.

$scope.myfruit = "1"; 

Check the below working example

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {

  var fruits = {
    "0": "apple",
    "1": "pear",
    "2": "banana"
  }

  $scope.items = fruits;
  $scope.myfruit = "1"; 


});
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="[email protected]" src="https://code.angularjs.org/1.4.12/angular.js" data-semver="1.4.9"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    
    <select class='form-control capitalize' name="cost" 
    ng-model="myfruit"              
    ng-options="key as val for (key, val) in items" >                       
    </select>
  
    
  </body>

</html>