有没有办法获取您的模块在任何时间点使用的绑定总数(通过模板' {{ .. }}
/ ng-xxx="..."
,等挂钩)?$scope.$watch(...)
2 回答
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.
下面是一篇关于如何使用浏览器控制台随时执行此操作的文章。如果您启动了多个应用程序,该文章还包含用于获取绑定数量的代码。
http://intervalia.blogspot.com/2015/01/how-to-determine-number-of-bindings-in.html