Call jquery plugin in directive only after data is renderer in DOM

心已入冬 提交于 2019-12-06 16:15:02

问题


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

});

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

        });
    }
};

});


回答1:


If you need the DOM to render first, use $timeout.

If you only need the DOM to be updated (but not rendered yet), use $evalAsync. Try this one first, as it may prevent flicker.



来源:https://stackoverflow.com/questions/16507377/call-jquery-plugin-in-directive-only-after-data-is-renderer-in-dom

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