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?
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();
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();
I recommend AngularJS Batarang. It's a debugging tool that lets you visualize all the scopes on the page (among other things).
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)
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).
You should develop your application in Google Chrome browser (if you are not using it already) and than you can use awesome Batarang extension that adds new dedicated AngularJS panel to the Developer tools. You can see all the scopes there, what is the relationships between them and what value have all its attributes.
http://blog.angularjs.org/2012/07/introducing-angularjs-batarang.html
In Angulars there is $rootScope
, which is the root of every scope.It has child field and whole hierarchy is inside $rootScope.If you want to find a scope with html element,you will probably have a problems,because that scope can be Isolated scope.Maybe you have a directive there,which scope is isolated.If you have anything like that,try to use el.isolatedScope()