Bob Yuan
Bob Yuan

Reputation: 588

Is there a way to get a scope of a DOM element when debug info is disabled?

I'm writing an directive which need to retrieve a scope of current DOM element. using the non public api angular.element().scope();

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?

Upvotes: 9

Views: 2175

Answers (1)

konakevin
konakevin

Reputation: 136

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;
    };
};

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

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

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!

Upvotes: 11

Related Questions