为什么使用 angularJs 的 select 选项显示第一个空选项?

Why does select option using angularJs show first empty option?

当我重新加载页面时,第一个选项总是空的。我希望包含文本 Any Make 的选项成为默认的 select 选项。这是我的观点的代码:

  <select class="form-control" id="make" name="make" ng-init="Any Make" ng-model="makeSelected" ng-change="makeChanged()">
      <option value="0" selected="selected"> Any Make</option>
      <option ng-repeat="obj in makeData" value="{{obj.make_id}}"> {{ obj.make_name | uppercase }} </option>
  </select>

这是我的控制器代码:

.controller("homeController", function ($scope, makeData, $http) {

            $scope.makeData = makeData;

            $scope.makeChanged = function () {
                $http({
                    method: "GET",
                    url: "homeService.asmx/GetModelById"})
                    .then(function (response) {
                        $scope.modelData = response.data;
                })
            }
        })

如果你不打算使用 ngOptions,至少去掉那个 ng-init 因为它不是一个函数,并且在控制器函数中设置 $scope.makeSelected = 0

然后您可以删除该初始选项上的 selected="selected",因为 angularJS 代码将处理所选内容。

请看下面的演示:

angular.module('app', [])
  .value('makeData', [{
    "make_id": 1,
    "make_name": "cat"
  },{
    "make_id": 2,
    "make_name": "dog"
  },{
    "make_id": 6,
    "make_name": "monkey"
  }])
  .controller("homeController", function($scope, makeData, $http) {
    //initialize the value associated with ng-model on the select list
    $scope.makeSelected = 0;
    $scope.makeData = makeData;

    $scope.makeChanged = function() {
      console.log('makeChanged');
      //$http() request removed because we don't have access outside this domain for AJAX requests.
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="homeController">
  <select class="form-control" id="make" name="make"  ng-model="makeSelected" ng-change="makeChanged()">
      <option value="0"> Any Make</option>
      <option ng-repeat="obj in makeData" value="{{obj.make_id}}"> {{ obj.make_name | uppercase }} </option>
  </select>
  <div>makeSelected: {{makeSelected}}</div>
</div>

只需删除 ng-init 并在您的模型中提供默认值

   $scope.makeSelected = 0;

这是您的代码 运行 fiddle Click here

Fiddle 用于包含动态数据的代码 Click here