Search code examples
javascriptangularjsng-optionsangular-ngmodel

Using ng-options to show object property but bind index with ng-model


I'm trying to display a list of the names of the teams in a league, and select one. When selected, it should place the index of league.teams[index] into homeTeam.teamId. Here is the HTML:

<select
    ng-model="homeTeam.teamId"
    ng-options="team.name for team in league.teams">
</select>

And here the scope:

$scope.league = {
    teams: [
        { name: "Team#1" },
        { name: "Team#2" }
    ]
};

But it adds the whole object into homeTeam.teamId, like this:

homeTeam: {
    "teamId": { "name":"Team#1" }
}

How can I get it to just input the index, i.e.:

homeTeam: {
    "teamId": 0
}

Solution

  • If you want an id then the teams should have one:

    ng-options="team.id as team.name for team in league.teams"

    Alternative:

    ng-options="league.teams.indexOf(team) as team.name for team in league.teams"

    indexOf() is not supported by IE < 9