AngularJS:如何优化嵌套指令

时间:2015-08-02 10:05:53

标签: javascript angularjs optimization angularjs-directive

我有角度指令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表示的每个小部件都有自己的逻辑,并且会基于其他一些呈现参数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;
}

1 个答案:

答案 0 :(得分:0)

我不知道为什么你需要大量的IF语句,为什么你需要使用指令,但我可以帮助你提供ng-repeat的建议。

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

此外,如果您有许多需要渲染的元素的接口,您可能应该查看ReactJS,这样渲染速度更快。