In my Angular app I have the following <select>
element that is populated like so:
HTML
<select name="device[ [[$index]] ]" ng-model="selectedModel" ng-change="loadModelImage(selectedModel)">
<option value="">Model</option>
<option ng-repeat="model in manufacturerModels" value="[[model.id]]">[[model.model]]</option>
</select>
JS
$scope.manufacturerModels = $filter('filter')($scope.models, {manufacturer_id: manufacturerId});
The above AngularJS snippet will return a JSON response of handset models stored in the API. (I'd post an example here but each object is quite lengthy).
Anyway, inside each 'model' is a sub-array of variants -- objects containing colours and memory sizes available for that device.
eg:
{
model: "iPhone 6",
manufacturer: "Apple",
variants: [
{
color: "space grey",
memory: "128GB"
}
{
color: "gold",
memory: "16GB"
}
{
color: "space grey",
memory: "64GB"
}
]
}
The Goal
I'd like to know if it's possible (and if so, how) to populate the model dropdown's <option>
's with the variants in the name. So where it currently says [[model.model]]
(.model being the name), I need each option to say something like: "iPhone 6 space grey 128GB"
PS. Angular interpolation temp. changed to [[ ]]
due to the same pages using mustachePHP.
You need to use the 'ngOptions' directive for that purpose. https://docs.angularjs.org/api/ng/directive/select The directive can take either an array of options or a hash (object) of options. And omit the 'ngRepeat' within 'option'.
I'm not sure I understand your question, but you can divide the models in optgroups and then have an option for each variant within each model:
Please see this plunkr: http://plnkr.co/edit/rPNaGXEi0m9rvNkzQuBJ?p=preview
Alternatively, you have to flatten your array:
And then you can use ngSelect:
Here's the updated Plnkr: http://plnkr.co/edit/rPNaGXEi0m9rvNkzQuBJ?p=preview
This may not be the answer you're looking for, but AngularJS is always pushing you to work with view-models, meaning models tailored for the views.
Your example with the models & its nested variants is not a model which is tailored for the view you're trying to present, and so I would suggest creating a new model based on your current model.
This new model would have one entry per model per variant, and would be flat so that a single ng-repeat would easily iterate over them. You could even add a watch statement to "manufacturerModels", so that you can be sure the new model you create for the options ng-repeat is always up to date.
Another option, which would work with what you're trying to do would be to create a simple directive, which only copies its inner html without its tags, for example:
I'll leave it to you to write this directive, as its fairly simple.
Then, to solve your problem you'd simply need to write a nested ng-repeat statement, something like this:
The rendered html should simply provide a long list of option tags which have all the options you want.