Call jquery plugin in directive only after data is

2020-08-01 08:30发布

问题:

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.