【问题标题】:Angular 1.5 and multiple nested data structureAngular 1.5 和多重嵌套数据结构
【发布时间】:2016-09-26 21:18:40
【问题描述】:

我有一个类似于这个例子的嵌套结构:

let structure = [{
  section: '1',
  title: 'First lvl title',
  children: [{
    section: '1.1',
    title: 'Second lvl title',
    children: []
  }, {
    section: '1.2',
    title: 'Second lvl title',
    children: [{
      section: '1.2.1',
      title: 'Third lvl title',
      children: []
    }, {
      section: '1.2.2',
      title: 'Third lvl title',
      children: []
    }]
  }, {
    section: '1.3',
    title: 'Second lvl title',
    children: []
  }]
}, {
  section: '2',
  title: 'First lvl title',
  children: [{
    section: '2.1',
    title: 'Second lvl title',
    children: []
  }, {
    section: '2.2',
    title: 'Second lvl title',
    children: []
  }]
}, ...other objects]

如您所见,结构类似于目录 - 我有代表单元的对象,每个单元都有自己的节号、标题和带有小节的数组。

数据的特点是我永远不知道我有多少个部分以及有多少嵌套的子部分。我需要假设我可以使用不同的配置获得大约 2 000 个对象(也许更多)。此外,我无法预测最大嵌套级别,并且对于特定部分可能会有所不同。

我正在尝试找到将这种结构表示为 HTML 页面的最优化方式。我正在考虑使用 ng-repeat 但我不知道这是否是一个好主意,因为我不知道我会有多少深度级别。此外,在生成我的 HTML 页面后,我可以删除一个部分(例如第 1 部分),并且我需要重新计算其他部分和小节的部分编号(第 2 节现在是第 1 节,第 2.1 小节现在是第 1.1 小节,依此类推)。在如此大量的数据上处理此操作的最佳方法是什么?

【问题讨论】:

  • 嗯,2000 个对象。我认为 Angular 不会喜欢 2000 绑定。 ng-repeat 将在阵列上放置一个手表。因此,添加或删除的任何内容都将反映在您的视图中。 ng-if 可以处理数据中的不可预测性。
  • 用户一开始不能吸收那么多。您将需要一些递归模板,但您还需要找出过滤或分页大量数据的方法。正如@Mikey 指出的那样,还会存在性能问题...... 2000 个对象将有多个 x 2000 个绑定

标签: javascript angularjs performance optimization data-structures


【解决方案1】:

您需要一个递归模板,其中结构是什么或数据的深度无关紧要。您可以使用递归自定义指令或递归 ngInclude:

<script type="text/ng-template" id="categoryTree">
    {{ category.title }}
    <ul ng-if="category.categories">
        <li ng-repeat="category in category.categories" ng-include="'categoryTree'">           
        </li>
    </ul>
</script>

http://benfoster.io/blog/angularjs-recursive-templates

【讨论】:

  • 递归模板是一个有趣的想法,但我不确定是否需要 ng-repeat 循环。使用 ng-repeat 循环 可能会很昂贵,因为它正在创建新的绑定,也许我应该使用 for 循环 来代替。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-18
  • 2014-04-27
  • 2018-03-16
  • 2022-01-22
  • 2011-09-27
  • 2020-01-31
  • 1970-01-01
相关资源
最近更新 更多