仅在数据在 DOM 中渲染后才在指令中调用 jquery 插件 [英] Call jquery plugin in directive only after data is renderer in DOM
问题描述
我想在 angular 指令中初始化一个 jquery 插件,但只有在返回服务数据和 DOM 中的第一个渲染器之后.我似乎可以弄清楚如何在角度指令中做到这一点.到目前为止,我有这段代码,但似乎我是在服务数据到达之后调用插件,但在它是 DOM 上的渲染器之前......有什么提示吗?
I want to initialize a jquery plugin in an angular directive but only after the service data is returned and first renderer in the DOM. I can seem to figure out how to do this in angular directive. I have this code so far, but it seems that i am calling the plugin after the service data arrived, but before it is renderer on the DOM... Any hints?
myApp.directive('myDirective', function () {
return {
restrict: 'A',
link: function ($scope, element, attrs) {
$scope.$watch("data.length", function( newValue, oldValue ) {
if ( newValue === oldValue ) {
console.log( "Should return..." );
return;
}
$(element).elastislide();
});
}
};
});
=== 编辑 ====如果我使用有效的 setTimeout 函数推迟执行,这是正确的方法吗?
=== EDIT ==== If i postpone the execution using the setTimeout function it works, is this the right way to do this?
myApp.directive('myDirective', function () {
return {
restrict: 'A',
link: function ($scope, element, attrs) {
$scope.$watch("data.length", function( newValue, oldValue ) {
if ( newValue === oldValue ) {
console.log( "Should return..." );
return;
}
postpone = $timeout(function() {
$('#carousel').elastislide();
}, 100);
});
}
};
});
推荐答案
如果您需要 DOM 先渲染,请使用 $timeout.
If you need the DOM to render first, use $timeout.
如果您只需要更新 DOM(但尚未呈现),请使用 $evalAsync.先试试这个,因为它可以防止闪烁.
If you only need the DOM to be updated (but not rendered yet), use $evalAsync. Try this one first, as it may prevent flicker.
这篇关于仅在数据在 DOM 中渲染后才在指令中调用 jquery 插件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!