Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get total number of bindings in your app/module

Tags:

angularjs

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?

like image 571
jlb Avatar asked Oct 15 '13 15:10

jlb


2 Answers

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.

like image 67
Andyrooger Avatar answered Nov 04 '22 07:11

Andyrooger


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

like image 44
Intervalia Avatar answered Nov 04 '22 07:11

Intervalia