Holt
Holt

Reputation: 452

Angular Formly - Select input with object

Please look at the following jsbin. I have a select input that has two options (Ohio, NewYork). Within the ng-options for the Select, I am selecting the entire object and NOT just the name or key value. I need both.

When I select Ohio (for example), the model correctly updates showing the selected object:

"birthState": {    
    "Key": "1",    
    "Value": "Ohio"  
}

If I add this code to the model within my controller (setting the field to 'Ohio' by default), the select does not reflect this default setting.

What am I doing wrong that is preventing me from giving this dropdown a default value?

Upvotes: 0

Views: 3038

Answers (1)

Sasikumar D.R.
Sasikumar D.R.

Reputation: 862

You are not able to select because, all objects will have unique id. objects in options array and object assigned in model (in controller) will be different in this way.

To achieve what you wanted, try adding track by option.Key in ng-options, and assign Key for 'birthState' field of model inside controller.

<script type="text/ng-template" id="select.html">
      <select required type="number" ng-model="model[options.key]" ng-options="option.Value for option in to.options track by option.Key">
           <option value="">Select One</option>
      </select>
</script>

inside controller

vm.model = {
      "birthState": {Key: '3'}
    };

Upvotes: 1

Related Questions