Illidan Illidan - 4 months ago 9
AngularJS Question

How to wrap $digest()?

I need to measure $digest duration inside my Angular application (performance monitoring).

Ideally, I would like to take time just before starting

$digest()
and and another one just after it executed.

I planned to wrap
$digest
function with my code, something like this (pseudo code):

function $digest(){

1. take timestamp
2. call to original $digest()
3. take timestamp
}


This wrapping should be transparent to the rest of the application, so everyone just keep call
$scope.$digest()
without any knowledge about this wrap. I want to avoid any modifications to
angular.js


Question: how I can do this? [Using Angular 1.3]

Answer

You need to override $digest in prototype of rootScope.

angular.module('myModule', []).run(run);

function run($rootScope) {
    var scopeProto = Object.getPrototypeOf($rootScope);
    var originalDigest = scopeProto.$digest;
    scopeProto.$digest = function(){
        console.log("Hello from digest!");
        originalDigest.call(this);
    }
}

Fiddle (open console to see result).