Pacuraru Daniel
Pacuraru Daniel

Reputation: 1205

directive to rotate a div with angularjs

i am tryin to make a directive with angular, to rotate a div infinite. Let's say i got this html

<div class="card" pendulum></div>

i created a directive like this to change the rotation

pdany.directive('pendulum', function() {
        return function(scope, elem, attr) {
            elem.css({
                    '-moz-transform': 'rotate(90deg)',
                    '-webkit-transform': 'rotate(90deg)',
                    '-o-transform': 'rotate(90deg)',
                    '-ms-transform': 'rotate(90deg)'
                });
        }
    });

but this directive changes the rotation css and that's it, but now i try to add a timer inside the directive but i have no idea how to do that. Is there a way to make it work only in directive, or i have to add something in controller too? Thank you for help, Daniel!

Upvotes: 3

Views: 4578

Answers (2)

iConnor
iConnor

Reputation: 20189

Without knowing how you want the element to rotate i can only suggest the following.

pdany.directive('pendulum', function() {
    return function($scope, $element, $attributes) {
       var degrees = 360;

       $element.css('transition', '-webkit-transform 800ms ease');

       var rotate = function() {
          $element.css('-webkit-transform', 'rotate(' + degrees + 'deg)');
          degrees += 360;
          setTimeout(rotate, 1000);
       };

        rotate();
    }
});

Demo: http://jsfiddle.net/kWvp6/3/

Upvotes: 3

fernandopasik
fernandopasik

Reputation: 10453

You should use css3 animations.

For example you should have in your stylesheet

@-webkit-keyframes rotate360{
    from {
        -webkit-transform:rotate(0deg);
    }
    to {
        -webkit-transform:rotate(360deg);
    }
}
@-moz-keyframes rotate360{
    from {
        -moz-transform:rotate(0deg);
    }
    to {
        -moz-transform:rotate(360deg);
    }
}
@-ms-keyframes rotate360{
    from {
        -ms-transform:rotate(0deg);
    }
    to {
        -ms-transform:rotate(360deg);
    }
}
@-o-keyframes rotate360{
    from {
        -o-transform:rotate(0deg);
    }
    to {
        -o-transform:rotate(360deg);
    }
}
@keyframes rotate360{
    from {
        transform:rotate(0deg);
    }
    to {
        transform:rotate(360deg);
    }
}

and in your elem.css

elem.css({
    'animation':'rotate360 1s linear 0s infinite',
    '-webkit-animation':'rotate360 1s linear 0s infinite',
    '-moz-animation':'rotate360 1s linear 0s infinite',
    '-ms-animation':'rotate360 1s linear 0s infinite',
    '-o-animation':'rotate360 1s linear 0s infinite'
});

Upvotes: 2

Related Questions