猿问

如何计算页面上的手表总数?

在JavaScript中,有没有一种方法可以计算整个页面上有角度的手表的数量?


我们使用Batarang,但它并不总是适合我们的需求。我们的应用程序很大,我们对使用自动化测试来检查手表计数是否增加过多感兴趣。


在每个控制器的基础上计数手表也将很有用。


编辑:这是我的尝试。它在ng-scope类中将手表计入所有内容。


(function () {

    var elts = document.getElementsByClassName('ng-scope');

    var watches = [];

    var visited_ids = {};

    for (var i=0; i < elts.length; i++) {

       var scope = angular.element(elts[i]).scope();

       if (scope.$id in visited_ids) 

         continue;

       visited_ids[scope.$id] = true;

       watches.push.apply(watches, scope.$$watchers);

    }

    return watches.length;

})();


倚天杖
浏览 796回答 3
3回答

Cats萌萌

这是我在检查范围结构的基础上放在一起的一个棘手的解决方案。它“似乎”起作用。我不确定这有多准确,它肯定取决于某些内部API。我正在使用angularjs 1.0.5。&nbsp; &nbsp; $rootScope.countWatchers = function () {&nbsp; &nbsp; &nbsp; &nbsp; var q = [$rootScope], watchers = 0, scope;&nbsp; &nbsp; &nbsp; &nbsp; while (q.length > 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; scope = q.pop();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (scope.$$watchers) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; watchers += scope.$$watchers.length;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (scope.$$childHead) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; q.push(scope.$$childHead);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (scope.$$nextSibling) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; q.push(scope.$$nextSibling);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; window.console.log(watchers);&nbsp; &nbsp; };
随时随地看视频慕课网APP

相关分类

AngularJS
我要回答