在浏览一些AngularJS示例时,我看到重复和创建结构是多么容易。但是,我无法弄清楚如何执行以下操作。
假设我们有像
这样的json结构 {
"Asia": {
"India": {
"Bangalore": {},
"Mumbai": {},
"New Delhi": {}
},
"China": {
"Beijing": {},
"Shanghai": {}
}
},
"Europe": {
"France": {
"Paris": {}
},
"Germany": {
"Berlin": {}
}
}
}
我想要做的是 - 将此JSON结构转换为无序列表 - 此类结构的深度未知,并且可能更深入。如何使用动态执行重复Angular JS?
答案 0 :(得分:4)
您的JSON结构不佳,您正在使用属性名称来传输数据。
你真正想要的是这样的:
$scope.continents = [
{
name: 'Asia',
countries: [
{
name: 'India',
cities: [
'Bangalore',
'Mumbai',
'New Delhi'
]
},
{
name: 'China',
cities: [
'Beijing',
'Shanghai'
]
},
]
},
{
name: 'Europe',
countries: [
{
name: 'France',
cities: [
'Peris'
]
},
{
name: 'Germany',
cities: [
'Berlin'
]
},
]
}
];
那说......听起来你想做的是创建某种递归树指令。这有点棘手。您需要对结构进行标准化,以便可以递归检查它。然后你将不得不创建两个指令。一个用于列表,一个用于项目:
这是example of what I mean ...
function Item(name, items) {
this.name = name;
this.items = items || [];
}
app.controller('MainCtrl', function($scope) {
$scope.items = [
new Item('test'),
new Item('foo', [
new Item('foo-1'),
new Item('foo-2', [
new Item('foo-2-1'),
new Item('foo-2-2')
])
]),
new Item('whatever')
];
});
app.directive('tree', function() {
return {
template: '<ul><tree-node ng-repeat="item in items"></tree-node></ul>',
restrict: 'E',
replace: true,
scope: {
items: '=items'
}
};
});
app.directive('treeNode', function($compile) {
return {
restrict: 'E',
template: '<li>{{item.name}}</li>',
link: function(scope, elm, attrs) {
//MAGIC HERE!!!: this will do the work of inserting the next set of nodes.
if (scope.item.items.length > 0) {
var children = $compile('<tree items="item.items"></tree>')(scope);
elm.append(children);
}
}
};
});
答案 1 :(得分:2)
如果有人对“尽力而为”的方式感兴趣而没有创建指令(不是你不应该,而只是提供变体),这里有一个简单的例子:
http://jsbin.com/hokupe/1/edit
此处还有一篇博文和10-15分钟的视频,内容如下:
http://gurustop.net/blog/2014/07/15/angularjs-using-templates-ng-include-create-infinite-tree/
示例代码:
<script type="text/ng-template" id="treeLevel.html">
<ul>
<li ng-repeat="item in items">
<input type="checkbox"
name="itemSelection"
ng-model="item._Selected" />
{{item.text}}
<div ng-include=" 'treeLevel.html'"
onload="items = item.children">
</div>
</li>
</ul>
</script>
<div ng-include=" 'treeLevel.html' "
onload="items = sourceItems">
</div>