在 ng-repeat 中显示子数组 [英] Displaying sub-array in ng-repeat
问题描述
在我的 Angular 应用程序中,我有以下 元素,其填充方式如下:
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});
上述 AngularJS 代码段将返回存储在 API 中的手机模型的 JSON 响应.(我会在这里发布一个示例,但每个对象都很长).
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.
例如:
{
model: "iPhone 6",
manufacturer: "Apple",
variants: [
{
color: "space grey",
memory: "128GB"
}
{
color: "gold",
memory: "16GB"
}
{
color: "space grey",
memory: "64GB"
}
]
}
目标
我想知道是否可以(如果可以,如何)使用名称中的变体填充模型下拉列表的 .因此,它当前显示
[[model.model]]
(.model 是名称),我需要每个选项都这样说:iPhone 6 space gray 128GB"
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"
附注.角度插值温度由于使用 mustachePHP 的相同页面,更改为 [[ ]]
.
PS. Angular interpolation temp. changed to [[ ]]
due to the same pages using mustachePHP.
推荐答案
我不确定我是否理解您的问题,但是您可以在 optgroups 中划分模型,然后为每个模型中的每个变体提供一个选项:
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:
<select>
<option value="">Model</option>
<optgroup ng-repeat="model in data" label="{{model.model}}">
<option ng-repeat="variant in model.variants" value="{{model}}">{{ model.model + '-' + variant.color }}</option>
</optgroup>
</select>
请看这个plunkr:http://plnkr.co/edit/rPNaGXEi0m9rvNkzQuBJ?p=preview
Please see this plunkr: http://plnkr.co/edit/rPNaGXEi0m9rvNkzQuBJ?p=preview
或者,您必须展平您的数组:
Alternatively, you have to flatten your array:
$scope.flatten = function(){
var out = [];
angular.forEach($scope.data, function(d){
angular.forEach(d.variants, function(v){
out.push({model: d.model, variant: v.color})
})
})
return out;
}
然后你可以使用 ngSelect:
And then you can use ngSelect:
<select ng-model="myColor" ng-options="model.variant group by model.model for model in flatten()">
<option value=""> -- select -- </option>
</select>
这是更新的 Plnkr:http://plnkr.co/edit/rPNaGXEi0m9rvNkzQuBJ?p=preview
Here's the updated Plnkr: http://plnkr.co/edit/rPNaGXEi0m9rvNkzQuBJ?p=preview
这篇关于在 ng-repeat 中显示子数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!