AngularJS Rotate Directive

by vaiism

HTML

<script src="http://code.angularjs.org/angular-1.0.0rc4.min.js"></script>
<script src="http://code.jquery.com/jquery.min.js"></script>
<div ng-app="arrowApp" ng-controller="HeadingCtrl">
     <!--Setup an arrow facing upwards. Rotate the div using the rotate directive. 
         The degrees property is bound to the heading property of the HeadingCtrl -->
    <div class="arrow-up" rotate degrees="heading"></div>
</div>

CSS

.arrow-up {
    width: 0;
    height: 0;
    border-left: 20px solid transparent;
    border-right: 20px solid transparent;
    border-bottom: 20px solid black;
    margin-top:20px;
    margin-left:20px;
}

JavaScript

var module = angular.module('arrowApp', []);

//Setup an rotate directive. It will rotate the div by the degrees attribute
module.directive('rotate', function() {
    return {
        link: function(scope, element, attrs) {
            // watch the degrees attribute, and update the UI when it changes
            scope.$watch(attrs.degrees, function(rotateDegrees) {
                console.log(rotateDegrees);
                //transform the css to rotate based on the new heading
                element.css({
                    '-moz-transform': 'rotate(' + rotateDegrees + 'deg)',
                    '-webkit-transform': 'rotate(' + rotateDegrees + 'deg)',
                    '-o-transform': 'rotate(' + rotateDegrees + 'deg)',
                    '-ms-transform': 'rotate(' + rotateDegrees + 'deg)'
                });
            });
        }
    }
});

//Setup a controller that updates the heading property every 100 milliseconds + 2 degrees
function HeadingCtrl($scope, $defer) {
    var heading = 0;

    // a function to update the heading 10 degrees every quarter second
    function updateHeading() {
        $defer(function() {
            
            //update the heading 2 degrees
            heading = heading + 2;
            $scope.heading = heading;
            
            // schedule another update
            updateHeading(); 
        }, 100);
    }

    // schedule the initial heading update
    updateHeading();
}