【问题标题】:AngularJS: how to optimize nested directivesAngularJS:如何优化嵌套指令
【发布时间】:2015-10-24 14:01:34
【问题描述】:

我有以下模板用于指令item 的角度。项目在其范围内包含属性 type。基于这种类型,我需要渲染不同的模板。

<item ng-repeat="myItem in items track by myItem.id">
  <div ng-switch="::myItem.type">
    <div ng-switch-when="type1">
      Some complex html with a couple of ng-if and ng-include
    </div>
    <div ng-switch-when="type2">
      Some complex html with a couple of ng-if and ng-include
    </div>
    <div ng-switch-when="type3">
      Some complex html with a couple of ng-if and ng-include
    </div>
    <div ng-switch-when="type4">
      Some complex html with a couple of ng-if and ng-include
    </div>
    <div ng-switch-when="type5">
      Some complex html with a couple of ng-if and ng-include
    </div>
    <div ng-switch-when="type6">
      Some complex html with a couple of ng-if and ng-include
    </div>
  </div>
</item>

我想重新处理独立指令中的每个ng-switch-when,并提高 ng-repeat 的性能(现在它必须为每个项目制作 ng-include 并设置 innerHTML,这对浏览器来说甚至是一项繁重的操作对于 50 个项目的列表)。

所以我的问题是:

  • 如何将 ng-switch-when 改造成独立指令
  • 在这种情况下如何提高 ng-repeat 的性能

更新:

  • AngularJS: Parse HTML events in timeline 相关的问题是我想优化当前结构的原因之一。
  • 添加错过track by
  • 需要大量的ng-ifng-include 语句,因为ng-switch-when 表示的每个widget 都有自己的逻辑,并且将根据myItem 的一些其他参数呈现。

问题还在于我需要通过一些用户操作完全重建此项目列表。

顺便说一句:

在反应中我可以做类似的事情:

render: function() {
  //it's for two items, but can be extended for any number of templates
  var child = this.props.type === 'Type A' ? <TemplateA /> : <TemplateB />;

  return child;
}

【问题讨论】:

  • 根据您的代码猜测,我会说 switch 子句是独占的。我的假设正确吗?每个案例的内容如何——是相似还是完全不同?因为没有更多细节,我看不到关于 switch 子句的任何可能的改进。
  • @alesc ng-switch-on 里面的模板是相似的,但是有一些不同,不一样。我不确定是否理解您的问题,如果不清楚,请询问所有内容。
  • @alesc 在每个ng-switch-on 中我必须检查myItem 的状态,并基于它包含适当的模板。例如。在type3里面:ng-if="myItem.hasSomething &amp;&amp; myItem.state.isReady ng-include="some-template.html"
  • 你可以省略 switch 并且只有一个孩子 - 一个指令。然后该指令将动态更改模板(HTML 元素)。如果某些 HTML 元素是相似的,那么指令可以重用它。如果没有任何东西可以重用,那么您最终会在指令中使用相同的类似开关的代码。如果是这种情况,请不要更改任何内容,因为您不会改进任何内容。

标签: javascript angularjs optimization angularjs-directive


【解决方案1】:

我不知道您为什么需要大量 IF 语句,以及为什么要为此使用指令,但我可以为您提供有关 ng-repeat 的建议。

在 ng-repeat 中使用 track by $index 来提高性能。并查看有关 Angular 性能的文章,例如:11 Tips to Improve AngularJS Performance

另外,如果你有很多需要渲染的元素的接口,可能你应该看看 ReactJS 渲染速度更快。

【讨论】:

  • 谢谢,我用了,只是在我的sn-p中错过了。
  • 现在需要很多 if 语句,ng-switch-when 内部的小部件有它自己的逻辑 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-29
  • 1970-01-01
  • 2016-09-25
  • 1970-01-01
  • 2016-04-10
  • 1970-01-01
相关资源
最近更新 更多