angular1中ng-repeat效率优化方法:

1.当 ng-repeat 的数组被替换时, 它默认并不会重新利用已有的 Dom 元素,而是直接将其全部删除并重新生成新的数组 Dom 元素:

2.Dom 的频繁操作是非常不友好的, ng-repeat为什么不能利用已有的 dom 元素去更新数据呢?因为你没有把数组元素的标识属性告诉它,那么两次替换的时候它就没办法追踪了;

3.ng-repeat会为每一个元素加上一个hashkey $$hashKey来识别每一个元素,当我们从后端重新获取数据时,即使数据完全一样,但是由于hashKey不一样,

angular会删除之前的所有dom,重新生成新的dom,这样效率就会大大降低。可以理解为ng-repeat默认是 track by $$hashKey的。

所以,我们应该使用一些不会变的东西来作为标识,比如后端数据的id.

4.列如:

<li class="gwclist" ng-repeat = "gwc in data | orderBy:'-sqtime' track by gwc.ID" ng-click = "gwcdetail(gwc)">
  <h5>申请人:{{gwc.sqname}}<span class="pull-right color-dimgray">{{gwc.sqtime}}</span></h5>
  <span>用餐时间:{{gwc.mettime}}</span>
<p ng-class="{0:'color-lightyellow',1:'color-red',2:'color-blue',3:'color-dimgray'}[{{gwc.processState | showstyle}}]">流程状态:{{gwc.processState}}</p> <div class="button-bar" ng-if = "gwc.processState == '未提交'"> <a class="button button-small button-positive" ng-click="submit(gwc.ID)">提交</a> <a class="button button-small button-stable" ng-click="delete(gwc.ID)">删除</a> </div> </li>
优点:这样当重新获取数据时,由于ID没有变,angular就不会去删除原来的dom,只会更新其中的内容,不同的ID再添加新的dom。效率就能提升了;

5.注意:

track by要放在orderBy之后,否则会影响orderBy的效果;

当单一数组有重复元素时,需要使用track by $index来保证两个元素都会渲染,否则只会渲染一个;