rockon1
rockon1

Reputation: 77

How to use angular to populate the select drop down list from an object withing an object.

I have the following JSON Object

 $scope.items = [
    { id: 1, name: 'Red',sizes:[{size:'s'},{size:'b'}]  },
    { id: 2, name: 'Green',sizes:[{size:'s'},{size:'b'}]   },
    { id: 3, name: 'Yellow',sizes:[{size:'s'},{size:'b'}]   }];

I'm trying to create a select option like the one below

<select id="s1" >
    <option value="?" selected="selected"></option>
    <option value="Red S">Red S</option>
    <option value="Red b">Red b</option>
    <option value="Green S">Green S</option>
    <option value="Green b">Green b</option>
    <option value="Yellow S">Green S</option>
    <option value="Yellow b">Green b</option>

</select>

Is it possible to achieve this using ng-options, if not what are my other options using angular.

Upvotes: 2

Views: 1937

Answers (1)

jcc
jcc

Reputation: 1147

Anything is possible with Angular ;) But for something like this (the data in that shape), using option groups would be your only option. To display them as a straight list of options as you showed, you would have to flatten your object first, and then do a ng-options on the new object/array.

<select id="s1" ng-model="selected">
    <option value=""></option>
    <optgroup ng-repeat="item in items" label="{{item.name}}">
      <option ng-repeat="size in item.sizes">{{item.name + ' ' + size.size}}</option>
    </optgroup>
</select>

Check out this Plunkr.

Upvotes: 3

Related Questions