javascript 使用 angular.element 通过 $ID 获取范围对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32610912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:31:16  来源:igfitidea点击:

Use angular.element to get scope object by $ID

javascripthtmlangularjsangularjs-scope

提问by TheIntrepidSpiff

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.

我需要将数据从 angular 应用程序传递到在 angular 之外运行的脚本,因为我无权编辑 angular 应用程序的代码。

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.

使用 Chrome 的 Angular Batarang 和 NG-Inspector 扩展,我可以看到我需要从中提取的 JSON 对象,但我不知道如何开始。

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

例如,在 Angular Batarang 中,对象看起来像:

$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.elementbut I haven't had any successes.

我最初的想法是我可以使用它来抓住它,angular.element但我没有取得任何成功。

回答by scniro

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()

您可以确定该范围绑定到哪个元素,选择该元素,并通过angular.element. 假设这个范围附加到 element <div id="stuff"></div>,观察下面的例子,具体来说,调用.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

JSFiddle 示例- 演示



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.

scope() - 检索当前元素或其父元素的范围。需要启用调试数据。

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

它默认启用,禁用它会导致问题