Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A few short methods that are helpful in navigating around angular scopes and watchers. For debugging or learning/exploring.
# A few short methods that are helpful in navigating around angular scopes and watchers.
# Useful for debugging or learning/exploring.
# Given a scope, count its direct children
# Use the to tell (in the case of fancy nested directives) if you're cleaning up what you think you're cleaning up
countScopeChildren = (scope) ->
count = 0;
if scope.$$childHead
count++
cur = scope.$$childHead
while cur.$$nextSibling
count++
cur = cur.$$nextSibling
return count
# For a given dom element, count the number of scopes it and all of it's children have
# Return an array of scopes
getScopesByEl = (element) ->
scopes = []
if element.data().hasOwnProperty '$scope'
scopes.push element.data().$scope
angular.forEach element.children(), (childElement) -> countEm $ childElement
return scopes
# Usage:
scopes = getScopesByEl $ document.getElementsByTagName 'body'
console.log "#{scopes.length} scopes"
# Given an element, return an array of all the watchers on that element or any of it's DOM children.
getWatchesByEl = (element) ->
watchers = []
if element.data().hasOwnProperty '$scope'
angular.forEach element.data().$scope.$$watchers, (watcher) ->
watchers.push watcher
angular.forEach element.children(), (childElement) ->
getWatchesFromElement $ childElement
return watchers
# Usage:
watchers = getWatchesByEl $ document.getElementsByTagName 'body'
console.log "#{watchers.length} watchers"
# Log the total watchers on the root scope.
# Presumes the rootScope is on the body tag, you could also do this with angular.injector([module]).get('$rootScope')
# Uses scope traversal instead of DOM traversal, so will miss isolate scopes.
logTotalWatchersOnRootScope = () ->
watchers = []
$rootScope = angular.element('body').scope()
q = [$rootScope]
scope = null
while (q.length > 0)
scope = q.pop()
if scope.$$watchers
watchers.push scope.$$watchers
if (scope.$$childHead)
q.push(scope.$$childHead)
if (scope.$$nextSibling)
q.push(scope.$$nextSibling)
console.log "#{watchers.length} watchers"
watchers
# Log total scopes on root scope.
# Uses scope traversal instead of DOM traversal, so will miss isolate scopes.
logTotalScopesOnRootScope = () ->
scopes = []
$rootScope = angular.element('body').scope() # angular.injector([module]).get('$rootScope')
q = [$rootScope]
scope = null
while (q.length > 0)
scope = q.pop()
if scope
scopes.push scope
if (scope.$$childHead)
q.push(scope.$$childHead)
if (scope.$$nextSibling)
q.push(scope.$$nextSibling)
# console.log "#{scopes.length} scopes"
scopes.length
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.