在 AngularJS 中使用 ng-options、ng-repeat 和 ng-selected 初始化 select

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

我正在尝试让 select 从使用 AngularJS 预 select 的一个选项开始,当我提交带有预 select 的表单时,我只有一个问题selected 选项没有任何反应,我有 POST 400(错误请求),当我手动 select 选项并成功提交表单时问题消失。

这是 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>

和 JS:

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

问题出在 angular 在 HTML

中创建的选项 value="? undefined:undefined ?"
<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/

HTML

<div class="col-md-3" ng-app="risk">
                <div class="form-group" ng-controller="RiskLevels">
                    <select id="id_level" name="level" class="form-control"  ng-model="selectedLevel" ng-options="item.text for item in levels"/>
                     <option value=''>Select</option>
                    </select>
                </div>
            </div>

Javascript

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

    //initial default selected  
    $scope.selectedLevel = $scope.levels[0];

  }]);

这个 Whosebug 问题将解释为什么有一个空选项

Why does AngularJS include an empty option in select?

要解决您的问题,请添加:

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

完整 fiddle: http://jsfiddle.net/nrybr0rf/2/