Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use angular.element to get scope object by $ID

I need to pass data from an angular app to scripts that run outside of angular because I do not have access to editing the code of the angular app.

Using Angular Batarang and NG-Inspector extensions for Chrome, I can see the JSON object I need to pull from, but I am at a loss of how to start.

For instance, in Angular Batarang, the object looks like:

$id=5
name: "listing"
keys:
   0: "alpha"
   1: "beta"
alpha:
   user: "test"
   userID: "12345"
beta: 
   address: "555 Elm St"
   phone: 555.555.5555

My initial thought was I could grab it using angular.element but I haven't had any successes.

like image 607
TheIntrepidSpiff Avatar asked Sep 16 '15 14:09

TheIntrepidSpiff


1 Answers

you can determine which element that scope is bound to, select the element, and grab it's scope via angular.element. Assume this scope is attached to element <div id="stuff"></div>, observe the following example, specifically, the call to .scope()

<div ng-app="app" ng-controller="ctrl" id="stuff"></div>

<button onclick="getStuff()">get stuff</button>

var app = angular.module('app', []).controller('ctrl', function($scope) {
   $scope.inside = { 'name': 'guy', 'idk': 'blah' }
});

var getStuff = function() {
    var outside = angular.element(document.getElementById('stuff')).scope();
    console.log(outside.inside) // retrieved "outside" of AngularJS
}

JSFiddle Example - demo


Update

Per the docs, debug mode must be enabled.

scope() - retrieves the scope of the current element or its parent. Requires Debug Data to be enabled.

It's enabled by default, and disabling it will cause issue here

like image 153
scniro Avatar answered Sep 19 '22 13:09

scniro