我正在写一条指令,该指令需要检索当前DOM元素的范围.使用非公共api angular.element().scope();
I'm writing an directive which need to retrieve a scope of current DOM element. using the non public api angular.element().scope();
在angular 1.3引入新功能$compileProvider.debugInfoEnabled(false);之前,它一直工作良好,该功能主要旨在提高性能以避免在DOM元素中绑定数据.但是,当debugInfoEnabled()设置为false时,angular.element().scope()将返回undefined.因此,我必须找到另一种方法来获得DOM元素的范围,否则我必须重新设计代码逻辑.
It works well until angular 1.3 introduces a new feature $compileProvider.debugInfoEnabled(false); which mainly aims to improve performance to avoid bind data in DOM element. But when debugInfoEnabled() is set to false, angular.element().scope() will return undefined. So I must find another way to get the scope of an DOM element or I have to redesign my code logic.
有没有办法使之成为可能?
Is there a way to make this possible?
推荐答案使用$compileProvider.debugInfoEnabled(false);编译应用程序后,我在应用程序中遇到了类似的问题.我稍后需要访问某些指令的隔离范围,但无法使用isolateScope()方法.为了解决这个问题,我在Utils服务中创建了一个帮助函数,如下所示:
I just faced a similar problem in our application after compiling our app with $compileProvider.debugInfoEnabled(false);. I needed to later access some of our directive's isolate scope but couldn't use the isolateScope() method. To get around the problem, I created a helper function in a Utils service that looks like this:
this.setElementIsolateScope = function(element, scope) { element[0].isolateScope = function() { return scope; }; };然后在需要能够稍后访问隔离作用域的任何指令中,我在link()函数中称为此函数:由于element是jqLite对象,因此您需要在isolateScope()上设置isolateScope()函数c9>.您应该已经将包装了element和scope的jqLite传递给了链接函数,然后将其传递给服务方法.
Then inside any directive where I needed to be able to later access the isolate scope I called this function inside the link() function: Since element is a jqLite object, you need to set the isolateScope() function on element[0]. You should already have the jqLite wrapped element and scope already passed into your link function, which you then just pass to your service method.
Utils.setElementIsolateScope(element, scope);要在以后访问隔离范围,您将获得对元素的引用,然后执行此操作(假设child_element是对元素/指令的引用):
To then access the isolate scope later, you would get a reference to your element and then do this (assuming child_element is the reference to your element/directive):
var child_iso_scope = _.isFunction(child_element.isolateScope) && child_element.isolateScope();根据获取元素引用的方式,您可能需要像这样包装jqLite包装器:
Depending on how you are getting the reference to your element, you may need to wrap it a jqLite wrapper like this:
child_element = angular.element(child_element);然后使用与上述相同的方法来获取隔离范围.希望这会有所帮助!
And then just use the same way as above to get the isolate scope. Hope this helps!
更多推荐
禁用调试信息后,是否可以获取DOM元素的作用域?
发布评论