Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs Directive For jQuery Cycle Plugin

I built the site with AngularJs and JQuery Cycle Plugin. Everything was working great until I needed to move my html partials into separate folders. Now when I run my code I see the jQuery Cycle plugin stopped working. Googling around and I found that I need to create a directive that would preserve the jQuery Cycle functionality, but I have no Idea how to create a directive that would make my jQuery Cycle plugin work in an Angular Site.

Below is how it is in jQuery code and working condition

$(".items").cycle({  
fx:     'scrollHorz', 
speed:  'slow', 
timeout: 1000, 
next:   '.move-left',  
prev:   '.move-right' 
        });

And this one is a broken one which doesn't work using directive approach.

myAngularApp.directive('cycle', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
           $(".items").cycle({  
            fx:     'scrollHorz', 
            speed:  'slow', 
            timeout: 1000, 
            prev:   '.move-left',  
            next:   '.move-right' 
        });
        }
    };
});

Can someone tell me how to create a directive that would make Cycle plugin work in an Angular Site?

like image 361
Mike Avatar asked Jan 12 '23 05:01

Mike


2 Answers

You code should work with some little modifications:

myApp.directive('cycle', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
       $(element).cycle({
           fx: 'fade',
           timeout: 10
       });
    }
  };
});

Demo: http://jsfiddle.net/WK2Fg/1/

like image 102
codef0rmer Avatar answered Jan 16 '23 12:01

codef0rmer


Here's a working example of jquery cycle with ng-repeat: http://jsfiddle.net/9dGGb/1/.

I had to wrap the jquery cycle initialization in a setTimeout, because it doesn't work even if the priority is > 1000:

myApp.directive('cycle', function() {
    return {
        restrict: 'A',
        priority: 1001,
        link: function(scope, element, attrs) {
           setTimeout(function(){
               $(element).cycle({
                   fx: 'fade',
                   timeout: 10
               });
           }, 0);
        }
    };
});
like image 27
Stefano Castriotta Avatar answered Jan 16 '23 12:01

Stefano Castriotta