select 下拉列表在 AngularJs 中第一个选项为空白

select dropdown has first option blank in AngularJs

我动态创建了下拉菜单。这是我的代码和输出 -

<select class="form-control"
    ng-init="option.id = conditions.fieldId"
    name="conditon_dropdown"
    ng-model="conditions.fieldId"
    ng-change="getOptionsChoice(conditions, conditions.fieldId)"
    ng-options="option.id as option.placeholder for option in attribute_values">
</select>

输出:

<select ng-options="option.id as option.placeholder for option in attribute_values" ng-change="getOptionsChoice(conditions, conditions.fieldId)" ng-model="conditions.fieldId" name="conditon_dropdown" ng-init="option.id = conditions.fieldId.toString()" class="form-control ng-pristine ng-untouched ng-valid ng-not-empty">
  <option value="?" selected="selected"></option>
  <option label="Size" value="number:1">Size</option>
  <option label="Color" value="number:2">Color</option>
  <option label="Fit" value="number:3">Fit</option>
  <option label="Rise" value="number:4">Select Rise</option>
</select>

这里是自动创建的<option value="?" selected="selected"></option>我要选择我的默认第一个选项<option label="Size" value="number:1">Size</option>

编辑:我已经写了 $scope.conditions.fieldId = 1 这工作正常。但我的期权价值是动态的。它可以是字符串或整数。如何在没有控制器的情况下 HTML 进行管理?

将 Array 的第一个元素分配给 ng-model 元素,像这样

如果你的数组是attribute_values

$scope.ngModelElement = $scope.attribute_values[0].fieldId;

并在控制器中使用 $scope

定义 ng-model 元素

您需要将初始模型值设置为实际对象。

查看工作示例。

// Set by default the   value "carton"
$scope.selectedUserProfile= $scope.userProfiles[0];

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

function myCtrl ($scope) {
   $scope.userProfiles = [
     {id: 10, name: 'Carton'},
     {id: 27, name: 'Bernard'},
     {id: 39, name: 'Julie'},
  ];
 
  // Set by default the   value "carton"
  $scope.selectedUserProfile= $scope.userProfiles[0];
  
  $scope.userProfiles1 = [
     {id: 10, name: 'Carton'},
     {id: 27, name: 'Bernard'},
     {id: 39, name: 'Julie'},
  ];
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  Dropdown with first option selected
  <select  id="requestorSite" ng-model="selectedUserProfile" ng-options="userProfile as userProfile.name for userProfile in userProfiles">
  </select>
  <br/><br/>
  
  Dropdown with first option as blank
  <select  id="requestorSite1" ng-model="selectedUserProfile1" ng-options="userProfile as userProfile.name for userProfile in userProfiles1">
  </select>
  </div>