angular.js Getting the element from inside $evalAsync in directive

。_饼干妹妹 提交于 2019-12-11 23:12:53

问题


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:


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();
    });
    ...
}],


来源:https://stackoverflow.com/questions/20241360/angular-js-getting-the-element-from-inside-evalasync-in-directive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!