Mohaideen
Mohaideen

Reputation: 209

How to make directive rendering faster inside ng-repeat

I have some many items to load.

So I have give in ng-repeat. Under that, I am using one directive. So directive should load on every item.

Here, It is taking time to load basic view after complete all the items in ng-repeat.

So, I need to view(render) single by single item. Actually, view shouldn't wait for complete ng-repeat.

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

Here, I have watchers for graphParams and graphSite.

How can we write a code for this?

Upvotes: 1

Views: 490

Answers (1)

kodu.cloud
kodu.cloud

Reputation: 1600

There is no way to render faster, but you can do several tricks to make UI more responsive:

  • Use custom filter to determine when user is in a bottom of the view and render more values from original array.
  • Use "track by" expression to avoid additional rendering.

Here is a live example for you:

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

Track by:

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

Filter:

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
  }
})

The core idea is to pass rendering items limit to filter and check if page is scrolled to the bottom using window.onscroll event. Because of track by expression it won't take more time to render old items. Only new ones will be added to view.

Also, you need to pass scope to your filter in order to use $apply method.

Upvotes: 1

Related Questions