AngularJS: jQuery, Bootstrap Slider example

by niden

HTML

<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="http://code.angularjs.org/1.0.0rc8/angular-1.0.0rc8.js"></script>
<script src="https://raw.github.com/EightMedia/hammer.js/master/hammer.js"></script>
<script src="https://raw.github.com/EightMedia/hammer.js/master/jquery.hammer.js"></script>
<div ng-controller="MyCtrl">
    <hr /><hr />
    <div class="slide-box">
        <div class="slide-btn btn" 
            hammer-drag container=".slide-box" on-drag="dragged" on-dragstart="dragstart" on-dragend="dragend">
               >>slide>>
        </div>
    </div>
    <div class="menu" ng-style="{'margin-left': -(1-percent)*300}"><img src="http://placekitten.com/300/200" /></div>
    <h5>percent: {{percent}}</h5>
</div>

CSS

.slide-box {
    width: 200px;
    background: grey;
}

JavaScript

function MyCtrl($scope){
    $scope.percent = 0;
    $scope.dragged = function(left, top, xPercent, yPercent) {
        $scope.percent = xPercent;
    };
    $scope.dragstart = function() { console.log('dragstart') };
    $scope.dragend = function() { console.log('dragend') };
}

/* hammer-drag directive.  Restricted to element.
 * Attributes available:
 *   'container': 
 *      css selector. default='body'. 
 *      User cannot drag element outside of the container
 *   'on-drag', 'on-dragstart', 'on-dragstop': 
 *      scope functions to call on drag. 
 *      Will pass parameters: function(x, y, xPercent, yPercent)
 *      x and y are relative to the top left corner of the container element.
 *      the percent variables are the percent of distance through container,
 *      (from top left corner) that the element has moved.
 */

angular.module('myApp', []).directive('hammerDrag', function() {
    //These are overwritten if attrs are set
    var events = { 
        'onDrag': function(){},
        'onDragstart': function(){},
        'onDragend': function(){}
    };
    
    var linkFn = function(scope, elm, attrs) {
        //Save container and drag-elements
        var $el = jQuery(elm);
        var $contain = jQuery(attrs.container || 'body');
        
        //Evaluate event strings if they're given, turning them into funcs
        for (evtName in events) {
            if (attrs.hasOwnProperty(evtName))
                events[evtName] = scope.$eval(attrs[evtName]);
            console.log(evtName, events[evtName]);
        }
        
        $el
        .css('position', 'relative')
        .hammer({
            drag: true,
            drag_vertical: true,
            drag_horizontal: true,
            prevent_default: true
        })
        .bind('dragstart', function(evt) {
            evaluateDragEvent('onDragstart', evt);
        })
        .bind('drag', function(evt) {            
            evaluateDragEvent('onDrag', evt);
        })
       ...