Count Your Angular Watchers

In my day job we’re building a very large Angular app that is having some performance issues. So today I started trying to do bit of tuning.

One thing I suspected was that there were too many watches but I needed to verify this.

Thankfully I found the answer in Kent C. Dodds article on counting your application’s watchers.

Just paste the following snippet into the browser console and it’ll return the number watchers.

function getWatchers(root) {
  root = angular.element(root || document.documentElement);
  var watcherCount = 0;

  function getElemWatchers(element) {
    var isolateWatchers = getWatchersFromScope(element.data().$isolateScope);
    var scopeWatchers = getWatchersFromScope(element.data().$scope);
    var watchers = scopeWatchers.concat(isolateWatchers);
    angular.forEach(element.children(), function (childElement) {
      watchers = watchers.concat(getElemWatchers(angular.element(childElement)));
    });
    return watchers;
  }

  function getWatchersFromScope(scope) {
    if (scope) {
      return scope.$$watchers || [];
    } else {
      return [];
    }
  }

  return getElemWatchers(root);
}

getWatchers().length

Even better is that you can select DOM element on the Elements tab in the console and then execute getWatchers($0) and get watchers for only that element and it’s descendants.