Search code examples
angularjsng-options

Angularjs ng-options for an object


I have a form that collects information such as a singer's first and last name, 2 guitarists first and last names and a drummer's first and last name. I'm attempting to push these values into select tag with ng-options.

I can successfully get in the guitarists names to show up in the select drop down, but I can't seem to get the singer and the drummer to show up.

<select ng-model="band" ng-options="band.firstName for firstName in band"></select>

$scope.band = {"singer": {
  "firstName": "Dave",
  "lastName": "Grohl"
  },"guitarists": [
{
  "firstName": "Chris",
  "lastName": "Shiflett"
},
{
  "firstName": "Pat",
  "lastName": "Smear"
}],"drummer": {
"firstName": "Taylor",
"lastName": "Hawkins" }};

Here's a fiddle: http://jsfiddle.net/rfT7f/17/

Any insight would be appreciated.


Solution

  • With ngOptions, you have to use a consistent object (or array) structure like

    $scope.band = [
        {
          "firstName": "Dave",
          "lastName": "Grohl",
          "role": "singer"
        },
        {
          "firstName": "Chris",
          "lastName": "Shiflett",
          "role": "guitarist"
        },
        {
          "firstName": "Pat",
          "lastName": "Smear",
          "role": "guitarist"
        },
        {
          "firstName": "Taylor",
          "lastName": "Hawkins",
          "role": "drummer"
        }
    ];
    

    Then you can do cool things like group options together in your select:

    <select ng-model="bandMember"
        ng-options="artist.firstName group by artist.role for artist in band">
    </select>
    

    Edit:

    Forgot to mention your ngModel should point to where you want to store the selected option, in this case $scope.bandMember