Search code examples
angularjshtml-selectdropdownng-options

select dropdown has first option blank in AngularJs


I have dynamically created dropdown. Here is my code and output -

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

Output:

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

Here is automatically created <option value="?" selected="selected"></option> I want to selected my default first option <option label="Size" value="number:1">Size</option>

Edit: I have written $scope.conditions.fieldId = 1 this is working fine. But my option value dynamic. It may be string or integer. How to manage this in HTML without controller?


Solution

  • Assign your first element of Array to the ng-model element, like this

    If your array is attribute_values

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

    And define ng-model element in controller with $scope