很难弄清楚您的具体情况到底是什么问题,也许提供一个孤立的示例是有意义的,以便其他人可以提供帮助。
结果可能取决于您如何计算观察者。我从中获取了解决方案here https://medium.com/@kentcdodds/counting-angularjs-watchers-11c5134dc2ef.
Here is 一个笨蛋的例子 http://plnkr.co/edit/LBNxtyYuQuj9bKcxBryC按预期工作(添加或删除::
in ng-repeat
):
HTML
<!DOCTYPE html>
<html ng-app="app">
<head>
<script data-require="[email protected] /cdn-cgi/l/email-protection" data-semver="1.5.6" src="https://code.angularjs.org/1.5.6/angular.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-controller="mainCtrl">
<div>{{name}}</div>
<ul>
<li ng-repeat="item in ::items">{{::item.id}} - {{::item.name}}</li>
</ul>
<button id="watchersCountBtn">Show watchers count</button>
<div id="watchersCountLog"></div>
</body>
</html>
JavaScript
angular
.module('app', [])
.controller('mainCtrl', function($scope) {
$scope.name = 'Hello World';
$scope.items = [
{ id: 1, name: 'product 1' },
{ id: 2, name: 'product 2' },
{ id: 3, name: 'product 3' },
{ id: 4, name: 'product 4' },
{ id: 5, name: 'product 5' },
{ id: 6, name: 'product 6' },
{ id: 7, name: 'product 7' },
{ id: 8, name: 'product 8' },
{ id: 9, name: 'product 9' },
{ id: 10, name: 'product 10' }
];
});
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);
}
window.onload = function() {
var btn = document.getElementById('watchersCountBtn');
var log = document.getElementById('watchersCountLog');
window.addEventListener('click', function() {
log.innerText = getWatchers().length;
});
};
希望这可以帮助。