0
votes

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?

1
I guess the following link could help you. gitter.im/formly-js/angular-formly?at=5571e985777c17d06a1416fd - user4321
@user4321, that is close but that example only has a name. I need to get the name and the key. I am trying to pass the selected object and not just the selected name. - Holt
Seems odd. I don't think this is worthy of an answer, but here's a workaround for the specific case. I just changed the "Select One" default value in the select template in the HTML and put the key & value in the model. - aliigleed
This workaround is fine until you don't provide a value to set as. In which case, the select shows nothing and there is no longer a 'Select One' default. Sorry that this isn't 'worthy' of your time to answer, lol. Wow. - Holt
@Holt Haha, ambiguous "this" ftl. I meant my workaround wasn't worthy of consideration as an official answer. I tried a few other things, but I'm not good enough with this stuff to get you a permanent solution, hopefully someone else chimes in. - aliigleed

1 Answers

1
votes

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'}
    };