如何在ng-repeat中使指令渲染更快

时间:2016-10-25 09:35:33

标签: javascript angularjs

我要加载很多项目。

所以我放弃了ng-repeat。在那之下,我使用一个指令。所以指令应该加载每个项目。

此处,在完成ng-repeat中的所有项目后,需要花时间加载基本视图。

所以,我需要单个项目查看(渲染)单个项目。实际上,视图不应等待完整ng-repeat

<div ng-repeat="site in siteList>
<stock-chart graph-site="site" graph-params="graphParams" ></stock-chart>
</div>

在这里,我有graphParamsgraphSite的观察者。

我们如何为此编写代码?

1 个答案:

答案 0 :(得分:1)

无法更快地渲染,但您可以通过多种技巧来提高用户界面的响应能力:

  • 使用自定义过滤器确定用户何时位于视图底部 并从原始数组中渲染更多值。
  • 使用“track by”表达式以避免其他渲染。

以下是您的实例:

https://plnkr.co/edit/onSjuQL8aB3iXGBamP28?p=preview

跟踪:

<div ng-repeat="site in siteList | scrollFilter:this:100 track by site.id">

过滤器:

app.filter('scrollFilter', function() {
  var bottomScrolledCount = 1,
      scope = null;
  window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
      if (scope) {
        scope.$apply(function() {
          bottomScrolledCount++;
        })
      }
    }
  };
  return function(values, fscope, length) {
    scope = fscope;
    var filterResult = [];
    for (i = 0, len = Math.min(values.length, length * bottomScrolledCount); i < len; i++) {
      filterResult.push(values[i]);
    }
    console.log(filterResult.length);
    return filterResult
  }
})

核心思想是将渲染项限制传递给过滤器,并使用window.onscroll事件检查页面是否滚动到底部。由于表达式跟踪,渲染旧项目不会花费更多时间。只会添加新的视频。

此外,您需要将范围传递给过滤器才能使用$ apply方法。

相关问题