选择下拉列表在AngularJs中有第一个选项空白

时间:2016-09-16 11:04:59

标签: angularjs html-select dropdown ng-options

我已动态创建了下拉列表。这是我的代码和输出 -

<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中管理它?

2 个答案:

答案 0 :(得分:2)

将您的第一个Array元素分配给ng-model元素,如下所示

如果您的数组是attribute_values

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

使用ng-model

在控制器中定义$scope元素

答案 1 :(得分:2)

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

参见工作示例。

// 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>