-
Notifications
You must be signed in to change notification settings - Fork 199
/
ng-count-digest-cycles.js
48 lines (39 loc) · 1.41 KB
/
ng-count-digest-cycles.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/*
Adds a watch expression on the root scope that counts the number of times
it was called. After method stops, restores the original method and
prints number of times digest cycle was run.
Method can return a promise.
Typical use: see how many times the full digest cycle is triggered.
$scope.myMethod = function () ...
where $scope could be determined from element 'my-selector'
*/
(function countDigestCycles() {
var selector = 'button';
var methodName = 'doSomething';
var name = selector + ':' + methodName;
/* global angular */
var el = angular.element(document.getElementById(selector));
var scope = el.scope() || el.isolateScope();
console.assert(scope, 'cannot find scope from ' + name);
var fn = scope[methodName];
console.assert(typeof fn === 'function', 'missing ' + methodName);
var $rootScope = el.injector().get('$rootScope');
var count = 0;
$rootScope.$watch(function () {
count += 1;
console.log('digest cycle ran', count, 'times');
});
var $q = el.injector().get('$q');
scope[methodName] = function () {
count = 0;
// method can return a value or a promise
var returned = fn();
$q.when(returned).finally(function finishedMethod() {
scope.$$postDigest(function () {
scope[methodName] = fn;
console.log('restored', methodName);
});
});
};
console.log('wrapped', name, 'for measuring number of digest cycles');
}());