user1283776
user1283776

Reputation: 21784

List running controllers instances and their this variable in console?

I have a memory leak somewhere in my Angular application and am trying to find it.

Is it possible to list all running controller instances in the console and their this variables?

I know that I can type console.log(window) to print all variables, but I do not know how to navigate to controller instances from there.

Upvotes: 0

Views: 75

Answers (1)

Shashank Agrawal
Shashank Agrawal

Reputation: 25797

Well, you can very well access the scope of all controllers like this:

var ngControllers = document.querySelectorAll('[ng-controller]');

angular.forEach(ngControllers, function(controllerElement) {
    var scope = angular.element(controllerElement).scope();
    console.log(scope);
});

And, if you want to access all nested scopes regardless of ng-controller then you can also do like this:

var $rootScope = angular.element(document.querySelector('[ng-app]')).scope();

var q = [$rootScope];

while (q.length > 0) {
    var scope = q.pop();
    console.log(scope);
    if (scope.$$childHead) {
        q.push(scope.$$childHead);
    }
    if (scope.$$nextSibling) {
        q.push(scope.$$nextSibling);
    }
}

Upvotes: 1

Related Questions