Get total number of bindings in your app/module

All we need is an easy explanation of the problem, so here it is.

Is there a way to get the total # of bindings (hooked in via templates’ {{ .. }}/ng-xxx="...", $scope.$watch(...), etc.) that your module is using at any point in time?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You should be able to get a rough idea using document.getElementsByClassName("ng-binding").length. As explained here, this class is applied to elements with {{ ... }} or ng-bind bindings, so you can get the number or elements using bindings. It will miss any that are not defined this way though.

All expression bindings should be using $parse to interpret the expression so you could try adding some debugging code to this service in the angular source code if you are happy with a temporary measure. It should be easy to see when a binding is created, but harder to see when it is destroyed.

Looking at the current master, it looks like $parse will change for 1.2.0 which may make things easier in Chrome. For this you should be able to use the Chrome Developer tools to take a heap snapshot (from the ‘Profiles’ tab), and search for all objects with the Parser constructor.

You can also see the number of watchers you have across your app using something like this

var watchersPerScope = $('.ng-scope').map(function() {
  var s = $(this).scope();
  if(s.$$destroyed) return 0;
  return (s.$$watchers || 0) && s.$$watchers.length;
}).get();
var totalWatchers = 0;
for(var i=0; i<watchersPerScope.length; i++)
  totalWatchers += watchersPerScope[i];
console.log(totalWatchers);

I realise none of these are great solutions to what you are asking, but they are at least something. A final suggestion is that if you are doing this for performance reasons, Batarang for Chrome has a very good performance section.


In newer versions of angular (1.3.2+), you can also use

$rootScope.$countWatchers();

if you include the ngMock module in the page. See the docs here.

Method 2

Below is an article on how to do this at any time using the browser console. The article also included code to get the number of bindings if you have bootstrapped multiple apps.

http://intervalia.blogspot.com/2015/01/how-to-determine-number-of-bindings-in.html

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply