【发布时间】: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-if和ng-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 && myItem.state.isReady ng-include="some-template.html" -
你可以省略
switch并且只有一个孩子 - 一个指令。然后该指令将动态更改模板(HTML 元素)。如果某些 HTML 元素是相似的,那么指令可以重用它。如果没有任何东西可以重用,那么您最终会在指令中使用相同的类似开关的代码。如果是这种情况,请不要更改任何内容,因为您不会改进任何内容。
标签: javascript angularjs optimization angularjs-directive