【问题标题】:Improve speed of ng-repeat having ng-include inside提高具有 ng-include 的 ng-repeat 的速度
【发布时间】:2014-01-01 07:16:20
【问题描述】:

我正在使用 ng-repeat,其中有一个 div,其中 ng-include 在 json 数组上以区分包含的相同模板的范围,但是当数组大小增加时,这种方法会减慢页面的加载速度。任何人都可以提出一种提高渲染速度的方法或替代方法吗?我的方法在小提琴中得到了体现。

<script type="text/ng-template" id="/toBeIncluded.html">
    This is a partial with something unique:
    <input ng-model="partialVar.val" />
</script>

<div ng-controller="MyCtrl">
    <div ng-repeat="partialVar in partialStuff">
        <div ng-include src="'/toBeIncluded.html'">    
        </div>
    </div>
    <button ng-click="getValues()">Values</button>
    <div>{{fvalues}}</div>
</div>

fiddle showing my problem

【问题讨论】:

  • 使用 $timeout。看我的回答。

标签: angularjs angularjs-ng-repeat


【解决方案1】:

您可以使用 $timeout 来提高速度。

$timeout 中创建您的数组,以便通过在块中包含模板来更新视图。虽然它需要与当前一样多的时间,但它不会举起您的浏览器。请参阅下面的方法。

代码

var partialStuff = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n"];
$scope.partialStuff = [];

for(var i=0;i<partialStuff.length;i++)
{
    (function(index) {
        $timeout(function() {
            $scope.partialStuff.push(partialStuff[index]);
        },20);
    })(i);
}

希望对你有帮助。

【讨论】:

  • 您确定运行摘要周期和渲染包含任何大小模板的 dom 的时间是固定的吗?
  • 可能会有所不同,但我认为这不会造成任何问题。
  • 你也可以用一个非常简单的指令替换 ng-include,使用 '/toBeIncluded.html' 作为 templateUrl。
猜你喜欢
  • 1970-01-01
  • 2017-02-02
  • 2014-01-22
  • 2018-03-27
  • 2017-02-06
  • 2016-11-17
  • 1970-01-01
  • 2014-02-26
  • 1970-01-01
相关资源
最近更新 更多