Skip to content Skip to sidebar Skip to footer

How Can You Detect When Html Rendering Is Completed In Angularjs

I've done extensive research on this subject, but no matter what I do, I find it extremely difficult to achieve this objective. I want to execute code when all elements have been f

Solution 1:

I developed the following directive which is working well under Chrome and IE11:

app.directive('whenRenderingDone',  function($timeout, $parse){
    return {
        link: function (scope, el, attrs) {
            var lastCount;
            var lastTimer = 5000; // Initial timeout//Check counter every few seconds, if no change since last time, this means rendering is done.var checkRenderingDone = function (){
                var mainPromiseResolved = scope.mainPromiseResolved;
                lastCount = lastCount || -1;
                if (lastCount === el.find('*').length && mainPromiseResolved) {
                    console.log('Rendering done, lastCount = %i', lastCount);
                    var func = $parse(attrs.whenRenderingDone);
                    func(scope);
                } else {
                    lastCount = el.find('*').length;
                    console.log('mainPromiseResolved = %s, lastCount %i', mainPromiseResolved, lastCount)
                    console.log('Rendering not yet done. Check again after %i seconds.', lastTimer/1000.00);
                    stopCheckRendering = $timeout(checkRenderingDone, lastTimer); 
                    lastTimer = lastTimer - 1000;
                    if (lastTimer <= 0) {
                        lastTimer = 1000;
                    }
                    return stopCheckRendering;
                }
            }
            var stopCheckRendering;
            stopCheckRendering = checkRenderingDone();
            el.on('$destroy', function() {
                if (stopCheckRendering) {
                    $timeout.cancel(stopCheckRendering);
                }
              });
        }
    }
});

I hope this will be of help to you, and if you have any comment to improve, please let me know. See this to give you an idea about how it is working.

Tarek

Solution 2:

You can use $$postDigest to run code after the digest cycle completes. You can read more about the scope lifecycle here

// Some $apply action here or simply entering the digest cycle
scope.$apply(function () { ... });
...
scope.$$postDigest(function () {
  // Run any code in here that will run after all the watches complete// in the digest cycle. Which means it runs once after all the // watches manipulate the DOM and before the browser renders
});

Post a Comment for "How Can You Detect When Html Rendering Is Completed In Angularjs"