Search code examples
angularjsangularjs-ng-repeatng-options

Initializing select with ng-options, ng-repeat and ng-selected in AngularJS


I'm trying to get a select to start off with one option pre-selected using AngularJS, i have only one problem when i submit form with pre-selected option nothing happen and i have POST 400 (BAD REQUEST), problem vanish when i select options manually and form submitted successfully.

Here's the HTML:

<form role="form" novalidate >
<div class="form-group">
    <select id="id_level" name="level" class="form-control" ng-model="level" >
        <option ng-repeat="level in levels" ng-selected="{{level.name =='Low'}}" value="{{level.name}}">Level : {{level.name}}
        </option>
    </select>
</div>

and the JS:

var app = angular.module('risk', []);
  app.controller('RiskLevels', ['$scope', function($scope) {
    $scope.levels = [
      {name : "Low"},
      {name : "Medium"},
      {name : "High"}
    ];
  }]);

the problem is the option value="? undefined:undefined ?" created by angular in HTML

<select id="id_level" name="level" class="form-control ng-pristine ng-valid ng-touched" ng-model="level">
  <option value="? undefined:undefined ?"></option>
  <!-- ngRepeat: level in levels -->
  <option ng-repeat="level in levels" ng-selected="true" value="Low" class="ng-binding ng-scope" selected="selected">Level : Low</option>
<!-- end ngRepeat: level in levels -->
  <option ng-repeat="level in levels" ng-selected="false" value="Medium" class="ng-binding ng-scope">Level : Medium</option>
<!-- end ngRepeat: level in levels -->
  <option ng-repeat="level in levels" ng-selected="false" value="High" class="ng-binding ng-scope">Level : High</option>
<!-- end ngRepeat: level in levels -->
</select>

JS Fiddle: http://jsfiddle.net/faridmax/nrybr0rf/1/


Solution

  • This stackoverflow question will explain why there is an empty option

    Why does AngularJS include an empty option in select?

    To fix your problem, add this:

    $scope.level = $scope.levels[0].name;
    

    Full fiddle: http://jsfiddle.net/nrybr0rf/2/