如何从根角对象$ rootElement的 [英] How to get $rootElement from root Angular object

查看:156
本文介绍了如何从根角对象$ rootElement的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是找到一个任意角项目的根元素,如果所有我是对象。这显然​​不是很洁净,所以被攻击的解决方案就可以了。

My objective is to find the root element in an arbitrary Angular project if all I have is the angular object. This obviously isn't very kosher, so a hacked solution will do.

我的第一个方法,这是找([NG-APP]),但失败的自举应用程序。我一直在玩弄各种角度的模块,我已经打了僵局。

My first approach to this was to find("[ng-app]"), but this fails on bootstrapped apps. I've been playing around with the various angular modules, and I've hit an impasse.

我可以做 angular.injector(['NG'])。获得('$ rootScope')来获得root范围。为什么我不能只是做
angular.injector(['NG'])。获得('$ rootElement的')来获取根元素?

I can do angular.injector(['ng']).get('$rootScope') to get the root scope. Why can't I just do angular.injector(['ng']).get('$rootElement') to get the root element?

推荐答案

angular.injector 创建一个新的喷油器的功能,它不会返回与自举程序关联的

angular.injector creates a new injector function, it does not return the one associated with the bootstrapped app.

在角服务是在这个意义上的单身,他们仅在每喷射一次,这意味着以下code:

Services in Angular are singletons in the sense that they are only created once per injector, which means that the following code:

angular.injector(['ng']).get('$rootScope')

将创建一个新的喷油器功能和新的 $ rootScope 每次执行的时间。

以下行:

angular.injector(['ng']).get('$rootElement')

将创建一个新的喷油器功能,并尝试恢复 $ rootElement的,它不为新创建的喷油器存在。

Will create a new injector function and try to retrieve the $rootElement, which does not exist for the newly created injector.

您需要检索当前应用程序的喷油器:

You need to retrieve the injector of the current app:

angular.element(DOMElement).injector();

有关您的特定情况下,可以例如查找与范围关联的第一个元素,并从那里:

For your specific case you can for example find the first element that is associated with a scope and go from there:

var element = document.querySelector('.ng-scope');
var $rootElement = angular.element(element).injector().get('$rootElement');
console.log($rootElement);

演示: http://plnkr.co/edit/mQ5ZibnV0Jg8DreXn0w9?p=$p$pview

这篇关于如何从根角对象$ rootElement的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆