Jthami05 Jthami05 - 4 months ago 12
AngularJS Question

How to pre-select option from <select> tag in Angular with options from a different controller?

I'm using two controllers here. One,

productComponentsController
, handles a call to our database that pulls back an array of
productComponent
objects. The other,
AddEditArticleController
, controls the 'Create New / Edit Existing Article' page.

On my Add/Edit Article page, I want a
<select>
to populate with
productComponents
, and, if I am editing an existing Article, to be pre-selected with that Article's current
productComponent
.

Simple as this seems, I cannot make the field pre-select with the existing
productComponent
, though it does populate the
<select>
with them correctly. I've tried ngRepeat and ngOptions and both work for populating the dropdown, but neither works for pre-selecting the existing
productComponentID
from the array returned by the server.

My HTML, using ngOptions:


<!-- productComponentsController as pvm, AddEditArticleController as vm -->
<select id="componentBox"
ng-model="vm.selectedComponent"
placeholder="Select a Product Component"
ng-change="vm.changeProductID()"
class="form-control input-md"
ng-options="component.name for component in pvm.productComponents track by component.id"></select>





My HTML, using ngRepeat:



<!-- productComponentsController as pvm, AddEditArticleController as vm -->
<select id="componentBox"
ng-model="vm.selectedComponent"
placeholder="Select a Product Component"
ng-change="vm.changeProductID()"
class="form-control input-md">
<option value="{{component.id}}"
ng-repeat="component in pvm.productComponents"
ng-selected="vm.selectOption(component.id)"
ng-bind-html="component.name"></option>
</select>
<!-- vm.selectOption() returns true if the current option's ID equals the productComponentID of the current Article. Therefore this option would be selected. -->





In my
AddEditArticleController
, I set vm.selectedComponent equal to the
productComponentID
of the Article that was returned by the database, in the promise.then() of my call. While
vm.selectedComponent
does change, this doesn't do anything to the dropdown.

Also, in my generated HTML, I get the option:
<option value="? number:47 ?"></option>
(for an Article where the productComponentID is = 47). Apparently this happens as a result of the model being set to an unknown value but I don't know why the model would be set to anything other than an integer id.

Is this because my select is accessing multiple controllers, or am I missing something obvious here? Any help is greatly appreciated, let me know if more info is needed.

Answer

So it turns out that because the model has to be a string, I have to cast the vm.selectedOption to a string whenever it's changed (in this case, in the vm.selectOption function) using String(). This is using ngRepeat. ngInit seems to have no bearing on how my code works.

Boom, that's it, and my code works.