Question

I want to use Jquery UI's accordion in AngularJS. So i wrote a directive:

angular.module('accordion', [])
    .directive('accordion', function () {
        return {
            restrict: 'AE',
            replace: true,
            link: function (scope, element, attrs) {
                $(document).ready(function () {
                    setTimeout(function () {
                        element.accordion({ icons: false });
                    }, 1000);
                });
            }
        };
    });

And I used the setTimeout because the directive is loaded before the page (or is it? I'm not sure), and so I need the timeout for it to be loaded. Of course the timeout is not always sufficient, and sometimes it is too quickly so I can see the HTML before the directive effect it, and then it changes to accordion and I don't want the users to see it.

Ideas?

Was it helpful?

Solution

Solved it... Added a watch in the directive - that watch a variable that changes when the data recieives from the server - and the accordion is activated!

angular.module('accordion', [])
    .directive('accordion', function () {
        return {
            restrict: 'AE',
            replace: true,
            link: function (scope, element, attrs) {
                scope.$watch('serverData', function (newValue, oldValue) {
                    if (oldValue != newValue) {
                        element.accordion();
                    }
                });
            }
        };
    });

OTHER TIPS

you dont need ($document).ready because directives are linked after angular bootstrapping process which in itself happens after the document is ready.

Now Im not sure what you are using the accordion with, if its image heavy, or uses other templates, its quite possible that this directive will be linked before all the images and ng-includes have loaded.

Can you create plunker with an example?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top