Search code examples
javascriptarraysjsonangularjsng-options

Looping over an array's indexes to populate ng-options' choices?


Hey guys I'm struggling trying to loop over productData.colors_and_sizes.data[i].sizes collection to put them into a single ng-option drop down.

The data set is straight forward but i've only used ng-option inside an array of strings.

image

Question:

Is it possible to loop over the productData.colors_and_sizes.data[x].sizes w/o transforming the data into an array of strings? I feel I just need to count over [i] but I dunno how :c

Html:

loop over productData.colors_and_sizes.data[i].sizes

   <select ng-model="item.mySize" ng-options="choice as choice for choice in productData.colors_and_sizes.data[i].sizes">
       <option value="">Please select a size</option>
   </select>

in the end, the values will be: Twin, Full, Queen, King.


Solution

  • <option ng-repeat="opt in options" value="{{opt.value}}">{{opt.text}}</option>
    

    that sort of thing should do it in general. So then the trick is getting your data in there. Assuming you're just using strings, it could be

    <option ng-repeat="item in productData.colors_and_sizes.data" value="{{item.sizes}}">{{item.sizes}}</option>
    

    It's a little weird to name the field 'sizes' when it seems to be a singular resource ("Twin" rather than ["Twin", "Full"...]), but as long as sizes is just a string, you can access it like the above.