0

I'm finding that I'm using scope.$evalAsync inside a directive quite a lot. Mainly to do DOM stuff/jquery plugins that need all the template {{vars}} compiled.

I can get at the scope object from inside $evalAsync but not the element. In latest case in question, I'm manipulating an element that gets rendered with an ngRepeat. I'm currently getting the element by composing a jquery selector based on the scope object e.g.

scope.$evalAsync(function (scope) {
    $("#item-" + scope.id).runJQplugin();
})

Although this works, to me it would be more intuitive to be able to do this

scope.$evalAsync(function (scope,element) {
    element.runJQplugin();
})

Am I approaching this right or have I misunderstood something fundamental with directives?

1 Answer 1

1

You always have access to the element from the link and the controller of a directive through the closure scope. So in link function:

link: function(scope, elem, attrs) {
    ...
    scope.$evalAsync(function(scope) {
        elem.runJQplugin();
    });
    ...
},

Controller (you need to specify the special $element dependency):

controller: ["$scope", "$element", function($scope, $element) {
    ...
    scope.$evalAsync(function(scope) {
        $element.runJQplugin();
    });
    ...
}],
Sign up to request clarification or add additional context in comments.

3 Comments

I've tried the top example in my directive and I'm getting ReferenceError: elem is not defined
A fiddle/plunk would help.
Your right I tried a barebones version in fiddle and it works, yet revisiting my code it definitely doesn't. So there's something weird I'm doing. Oh well I'm using $("#item-" + scope.id) for now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.