我有一个从API获得的JSON:
$scope.data = [{
"primary": "white",
"sub": ["white 1", "white 2", "white 3"]
},{
"primary": "black",
"sub": ["black 1", "black 2", "black 3"]
}];
我想按主要分组和可选择的值是数组子
喜欢:
**White**
white 1
white 2
white 3
**Black**
Black 1
Black 2
Black 3
我可以按主键分组,但我无法获得内在值。这就是我所拥有的:
<div ng-controller="myCtrl">
<select
ng-model="myOption"
ng-options="val.primary group by value.primary for value in data">
</select>
<div>
ng-model value: {{myOption}}
</div>
</div>
(这是我的小提琴:http://jsfiddle.net/jm6of9bu/648/)
答案 0 :(得分:3)
你需要弄平你的阵列。即使使用group by
,ng-options
也适用于平面阵列:
$scope.data2 = [
{primary: "white", sub: "white1"},
{primary: "white", sub: "white2"},
{primary: "white", sub: "white3"},
{primary: "black", sub: "black1"},
{primary: "black", sub: "black2"},
{primary: "black", sub: "black3"},
];
然后你可以这样做:
<select
ng-model="myOption"
ng-options="value as value.sub group by value.primary for value in data2">
</select>
模型将设置为value
对象 - 例如{primary: "white", sub: "white2"}
。如果您想将其设置为"white2"
,"black3"
等,请使用:
ng-options="value.sub as value.sub group by value.primary for value in data2"
答案 1 :(得分:0)
最后,我能够通过微调来解决这个问题:
这是我试过的
<div ng-controller="myCtrl">
<select ng-model="myOption" ng-options="value.sub group by value.primary for value in data2">
我将嵌套的JSON拼凑为:
function myCtrl($scope) {
datas = [{
"primary": "white",
"sub": ["white 1", "white 2", "white 3"]
},{
"primary": "black",
"sub": ["black 1", "black 2", "black 3"]
}];
$scope.data2 = [];
datas.forEach(function(entry){
entry.sub.forEach(function(sub){
$scope.data2.push({primary:entry.primary,sub:sub})
});
});
};
答案 2 :(得分:0)
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.data = [{
"primary": "white",
"sub": ["white 1", "white 2", "white 3"]
},{
"primary": "black",
"sub": ["black 1", "black 2", "black 3"]
}];
$scope.dataList=[];
$scope.data.forEach(function(value,index){
value.sub.forEach(function(temp,index){
$scope.dataList.push({
'groupType':value.primary,
'value':temp
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller="myCtrl">
<select
ng-model="myOption"
ng-options="data.value as data.value group by data.groupType for data in dataList">
</select>
<div>
ng-model value: {{myOption}}
</div>
</div>
答案 3 :(得分:-4)
我可能不完全明白你想要的是什么但是
如果您想要显示子值,请在分组前将val.primary更改为val.sub
<div ng-controller="myCtrl">
<select
ng-model="myOption"
ng-options="val.sub group by value.primary for value in datas">
</select>
<div>
ng-model value: {{myOption}}
</div>
</div>