使用 angular.element 通过 $ID 获取范围对象 [英] Use angular.element to get scope object by $ID
问题描述
我需要将数据从 angular 应用程序传递给在 angular 之外运行的脚本,因为我无权编辑 angular 应用程序的代码.
使用 Chrome 的 Angular Batarang 和 NG-Inspector 扩展,我可以看到我需要从中提取的 JSON 对象,但我不知道如何开始.
例如,在 Angular Batarang 中,对象看起来像:
$id=5名称:上市"键:0:阿尔法"1:测试版"α:用户:测试"用户 ID:12345"测试版:地址:555 Elm St"电话:555.555.5555
我最初的想法是我可以使用 angular.element
抓取它,但我没有成功.
您可以确定该作用域绑定到哪个元素,选择该元素,并通过 angular.element
.假设这个范围附加到元素
.scope()
<div ng-app="app" ng-controller="ctrl" id="stuff"></div><button onclick="getStuff()">获取东西</button>
<小时>
var app = angular.module('app', []).controller('ctrl', function($scope) {$scope.inside = { 'name': 'guy', 'idk': 'blah' }});var getStuff = function() {var 外部 = angular.element(document.getElementById('stuff')).scope();console.log(outside.inside)//检索到 AngularJS 的外部"}
JSFiddle 示例 - 演示
<小时>更新
根据 docs,必须启用调试模式.
<块引用>scope() - 检索当前元素或其父元素的范围.需要启用调试数据.
默认启用,禁用它 会在这里引起问题
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.
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
这篇关于使用 angular.element 通过 $ID 获取范围对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!