Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the scope's element outside the directive

Is there a trick to get the element associated with the scope outside the directive that owns it?

I act on the premise that it has to be done in least favorable conditions (from the console or Greasemonkey script). E.g. to get the element that has the scope

angular.element(document.querySelector('.ng-scope')).scope().$$childTail

without DOM traversing.

I guess it is possible to traverse all ng-scope and ng-isolate-scope DOM elements and map their scopes, yet I'm looking for more elegant solution (the map also needs to be kept up to date, and I'm trying to stay away from DOMSubtreeModified, also this won't work with debugInfoEnabled disabled).

like image 458
Estus Flask Avatar asked Apr 26 '15 14:04

Estus Flask


1 Answers

Scopes (src) don't keep a reference to the element they're associated with. After all, scopes can exist without being associated with a specific element.

$compile (src) is the one responsible for associating elements with scopes.

Part of the compilation process augments the element, letting you go from element >> scope (e.g. angular.element("#something").scope()). The same doesn't seem to happen with scopes.

So to go the other way, scope >> element, you have to map scope ids: Get DOM element by scope $id. That feature in Angular JS Batarang that lets you pick an element from the page and inspect the scope associated with it? This is how it's done. Batarang uses angular-hint. angular-hint iterates through all elements on the page with an ng-scope class and returns the one with a matching scope id (src: function findElt).

function findElt (scopeId) {
  var elts = document.querySelectorAll('.ng-scope');
  var elt, scope;

  for (var i = 0; i < elts.length; i++) {
    elt = angular.element(elts[i]);
    scope = elt.scope();
    if (scope.$id === scopeId) {
      return elt;
    }
  }
}
like image 119
user2943490 Avatar answered Oct 04 '22 11:10

user2943490