Use angular.element to get scope object by $ID

。_饼干妹妹 提交于 2019-12-07 06:04:30

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/32610912/use-angular-element-to-get-scope-object-by-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!