我有这样的JSON:
[
{
"name": "parent1",
"children":
[
{
"name": "child1",
"foo": "bar"
},
{
"name": "child2",
"foo": "bar"
},
{
"name": "child2",
"foo": "bar"
},
{
"name": "child3",
"foo": "bar"
}
]
},
{
"name": "parent2",
"children":
[
{
"name": "child1",
"foo": "bar"
},
{
"name": "child2",
"foo": "bar"
},
{
"name": "child2",
"foo": "bar"
},
{
"name": "child3",
"foo": "bar"
}
]
}
]
我想使用ng-repeat来呈现<select>
列表,如下所示:
<select>
<option disabled>parent1</option>
<option>child1</option>
<option>child2</option>
<option>child3</option>
<option>child4</option>
<option disabled>parent2</option>
<option>child1</option>
<option>child2</option>
<option>child3</option>
<option>child4</option>
</select>
然而,我似乎无法让它发挥作用。在Stackoverflow的另一个主题中,我看到了同样的问题,但是这只是使用常规div,并且一个div围绕父/子,所以你可以轻松地重复该div。但是,这里不可能。我试图将div和其他元素包装在每个家庭中,但是1)它的可怕代码,以及2)它甚至没有工作。
答案 0 :(得分:3)
将json作为$ scope.nodes,这样的事情应该可行
<select>
<option ng-repeat-start="node in nodes" disabled>{{node.name}}</option>
<option ng-repeat="child in node.children">{{child.name}}</option>
<option ng-repeat-end ng-show="false"></option>
</select>
答案 1 :(得分:1)
var children = [];
angular.forEach(source, function(parent) {
angular.forEach(parent.children, function(child) {
children.push({ name: child.name, parent: parent.name});
});
});
$scope.children = children;
$scope.selectedChild = $scope.children[0];
<select ng-model="selectedChild"
ng-options="child.name group by child.parent for child in children">
</select>
答案 2 :(得分:1)
这是一种可以用来将源json展平成扁平格式的方法,该格式易于在ng-repeat或ng-repeat-like指令中使用,例如ng-options:
$scope.options = []; // this will store the flattened array
angular.forEach(response, function(group) {
$scope.options.push({ name: group.name, isParent: true});
angular.forEach(group.children, function(child) {
$scope.options.push({ name: child.name, isParent: false});
});
});
你最终会得到一个像这样的数组:
[
{"name":"parent1","isParent":true},
{"name":"child1","isParent":false},
{"name":"child2","isParent":false},
{"name":"child2","isParent":false},
{"name":"child3","isParent":false},
{"name":"parent2","isParent":true},
{"name":"child1","isParent":false},
{"name":"child2","isParent":false},
{"name":"child2","isParent":false},
{"name":"child3","isParent":false}
]