1

I want to select the first option in a select box by default. The challenge here is that the page might have multiple select boxes as they are created dynamically.

You will understand what I am trying to achieve by looking at my code.

HTML :

<form class="form-inline">
    <div class="form-group form-group-grid" ng-repeat="fields in selectedTabData.requiredField" ng-switch="fields.paramType">
        <label>{{fields.paramName}}<span class="asterisk" ng-if="fields.mandatory==true">*</span></label>
        <input type="text" class="form-control" ng-switch-when="Text" ng-model="fields.fieldValue" ng-attr-id="{{fields.paramName}}Id">
        <select class="form-control" ng-switch-when="DropDown" ng-options="field.paramKey as field.paramValue for field in fields.paramData" ng-model="fields.fieldValue" ng-attr-id="{{fields.paramName}}Id">
        </select>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary form-inline-grid-button" ng-click="getReport()">Run Report</button>
    </div>
</form>

The selected data is available under the model $scope.selectedTabData.requiredField

In Controller I push the selected values in to a variable like :

$scope.selectedTabData.requiredField.forEach(function(item) 
        {
                paramValue.push(item.fieldValue);
                paramName.push(item.paramName);
 })

I tried doing this :ng-init="fields.fieldValue = fields.paramData[0]"

<select class="form-control" ng-switch-when="DropDown" ng-options="field.paramKey as field.paramValue for field in fields.paramData" ng-model="fields.fieldValue" ng-init="fields.fieldValue = fields.paramData[0]" ng-attr-id="{{fields.paramName}}Id">
                                    </select>

I am not sure how it will work. Can anyone help me out with this?

Phoenix
  • 285
  • 9
  • 28

2 Answers2

1

you can make it possible by ng-repeat inside tag

<select ng-model="fields.fieldValue">
     <option ng-repeat="field in fields.paramData" value="{{field.paramKey}}">
         {{field.value}}
     <option>
</select>

and in controller add this line

$scope.fields.fieldValue = x;

and in this example, x is "field.value" that you want as default selected option.

Mohammad.Gh
  • 385
  • 3
  • 16
  • $scope.selectedTabData.requiredField.forEach(function(item) { item.fieldValue = item.paramData[0].paramValue; }) – Phoenix Nov 20 '17 at 10:39
  • Is this how I should do it? The above code is not working for me – Phoenix Nov 20 '17 at 10:40
  • Never mind, I still had Ng-init in my html, thats why it was not working. I removed it and then, voilà... Thanks a lot – Phoenix Nov 20 '17 at 12:30
0
This is the plunkr for your problem

https://plnkr.co/edit/mahONdv5xQBa5eUZJSoX

john
  • 36
  • 4