Search code examples
javascripthtmlangularjsdata-bindingng-options

Angular: Getting error while using ng-option


I have this schema:

teams: [
   {
      id: 1,
      name: "Spain"
   },
   {
      id: 2,
      name: "Germany"
   }
]

now I have this select element:

<select ng-model="betSchema.winnerId" ng-options="team.name for team in teams track by team.id">
    <option value="-1">Tie</option>
</select>

the betSchema object looks like this (as default):

{
   winnerId: -1
}

Here is the result I see:

enter image description here

The problems are:
1. I can't see the tie option, and there is one mysteries "blank" option (the first at the top). 2. when the betSchema looks like this:

{
   winnerId: 2
}

I am expecting to see Germany option to be selected.

What am I doing wrong?


Solution

  • See this fiddle: http://jsfiddle.net/Mn4SH/4/

    There are a couple of things.

    1. When using ng-options Angular is going to overwrite your option tags so you have to add it to your model like such:

      scope.teams = [{ id: -1, name: "Tie" }, { id: 1, name: "Spain" }, { id: 2, name: "Germany", }];

    2. Second, you can use track by but using "as" would also work in this context: https://docs.angularjs.org/api/ng/directive/select. You can use obj.dataToBeStoredInModel as obj.labelOfData for obj in objList to get the id for ng-options.