In AngularJS, how do you find all the scopes on a page?
Solution 1
you can see all of the scopes on the page using this CSS selector
.ng-scope { border: 1px solid red; }
and all of the bindings:
.ng-binding { border: 1px solid red; }
You can then retrieve them by converting the DOM element into selector
var selector = angular.element(some_dom_element);
Then use the selector to retrive the scope/controller/injector
var scope = selector.scope();
var controller = selector.controller();
var injector = selector.injector();
Solution 2
Not all scopes are bound to elements. If you want all scopes on the page, walk the scope tree like this:
function getScopes(root) {
var scopes = [];
function visit(scope) {
scopes.push(scope);
}
function traverse(scope) {
visit(scope);
if (scope.$$nextSibling)
traverse(scope.$$nextSibling);
if (scope.$$childHead)
traverse(scope.$$childHead);
}
traverse(root);
return scopes;
}
getScopes($rootScope)
Solution 3
I don't know why this would be useful to you, but you can do this:
scopeElements = document.getElementsByClassName('ng-scope');
scopes = [].map.call(scopeElements, function(e){ return angular.element(e).scope(); })
The other option is to traverse the scope tree starting at the root scope using our private apis: $$childHead and $$nextSibling.
It's more likely that you just want to see where the scope boundaries are and you can do it with this:
scopeElements = document.getElementsByClassName('ng-scope');
angular.element(scopeElements).css('border', '1px solid red');
Then you can just use web inspector to select an element of interest and get its scope by:
angular.element($0).scope();
Solution 4
I recommend AngularJS Batarang. It's a debugging tool that lets you visualize all the scopes on the page (among other things).
https://github.com/angular/angularjs-batarang
Solution 5
You can find out a scope for element using:
$(element).scope()
or
angular.element(element).scope()
I don't think there is a way to get all scopes on a page easily (other than navigating down from root scope).
Comments
-
wl. almost 2 years
Once we have a scope in hand, we can navigate to its root and explore the scope hierarchy.
But is there a direct way to find all the scopes on a page?
Likewise given an HTML element, is there a direct way to find its enclosing scope?