Search code examples
angularng-options

ng-options not loading any options into select


My select choice list is empty using ngOptions or ngRepeat. New to Angular and I suspect scope issue - Angular docs and other posts here have not yet resulted in a solution.

Array of objects is definitely loaded - see code snippets below for what's working and what's not. 2 pieces that work, and one that does not.

<form name="aForm">
  <!--this works-enumerates the array of objects.  straight from tutorial-->
  <li *ngFor="let x of models">
    <span>{{x.id}}</span> {{x.name}}
  </li>

  <!--this works for showing data in the list, but yuk-->
  <select ng-model="selectedmodel" > 
    <option value="{{models[0].id}}">{{models[0].name}}</option>
    <option value="{{models[1].id}}">{{models[1].name}}</option>
    <option value="{{models[2].id}}">{{models[2].name}}</option>
    <option value="{{models[3].id}}">{{models[3].name}}</option>
    <option value="{{models[4].id}}">{{models[4].name}}</option>
  </select>

  <!--this does not work - produces an empty choicelist-->
    <select name="pricemodelselect"
            ng-model="selectedpricemodel"
            ng-options="x as x.name for x in models">
    </select>
</form>

Solution

  • Do a *ngFor on option instead of doing it on select. Try this:

    <select ng-model="selectedmodel"> 
        <option *ngFor="let x of models" value="{{x.id}}">{{x.name}}</option>
    </select>
    

    Whichever tag you put this structural directive on, will get iterated over all the values of the array.