gpt4 book ai didi

javascript - 在 ng-repeat 中循环遍历深层对象

转载 作者:行者123 更新时间:2023-12-03 11:23:07 26 4
gpt4 key购买 nike

我有 Angular ,我有一个这样的对象。

var items = [{
title: 'Something',
children: [
{ title: 'Hello World' },
{ title: 'Hello Overflow' },
{ title: 'John Doe', children: [
{ title: 'Amazing title' },
{ title: 'Google it' },
{ title: 'I'm a child', children: [
{ title: 'Another ' },
{ title: 'He\'s my brother' },
{ title: 'She\'s my mother.', children: [
{title: 'You never know if I'm going to have children'}
]}
]}
]}
]
}];
我不想遍历所有这些,所以我有这样的东西。

    • Something

       • Hello World

       • Hello Overflow

       • John Doe

          • Amazing Title

          • Google it

          • I'm a child

              • Another

              • He's my brother

              • She's my mother

                  • You never know if I'm going to have children


问题是我不知道这个物体会深入多深或里面有什么。所以我无法手动完成。我用 ng-repeat 做了一个基本的循环在底部提供的 fiddle 中,但我不知道如何自动循环遍历这些并创建嵌套 <ul>的和 <li>的。
实现这一目标的最佳方法是什么?
演示:http://jsfiddle.net/XtgLM/

最佳答案

您不需要创建自定义指令,您想要的是使用一个调用它自己的内联模板。

我 fork 了你的 fiddle 。

http://jsfiddle.net/MasterMorality/E99Gh/2/

基本上它看起来像这样:

<script type='text/ng-template' id="item.html">
...
<div ng-repeat="x in x.childrens" ng-include="'item.html'"></div>
</script>
...
<div ng-repeat="x in things" ng-include="'item.html'"></div>

我应该注意到您实际上并没有覆盖 x ,因为 angular 为每个重复项创建了一个新范围。

关于javascript - 在 ng-repeat 中循环遍历深层对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18408496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com