Draggable Bar Directive
by uohzxela
HTML
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="http://code.angularjs.org/angular-1.0.1.js"></script>
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<!doctype html>
<html ng-app="DraggableBar">
<body>
<div draggable percent="19%" height="30px" width="100%" bar-color="LightCoral"></div>
</br>
<div draggable percent="40%" height="60px" width="60%" bar-color="PaleTurquoise"></div>
</body>
</html>
JavaScript
angular.module('components', [])
.directive('draggable', function ($document) {
return {
restrict: 'A',
scope: {
percent: "@",
width: "@",
height: "@",
barColor: "@"
},
link: function (scope, elem, attr) {
var dragbar = elem.children().children('.dragbar');
dragbar.bind('mousedown', function ($event) {
$document.bind('mousemove', mousemove);
$document.bind('mouseup', mouseup);
});
function mousemove(e) {
console.log("mouse move");
e.preventDefault();
var bar = elem.children();
var pos = bar.children(".position");
console.log("sidebar width: " + bar);
bar.css("width", e.pageX);
console.log(scope.percent);
var width = bar.width();
var parentWidth = bar.parent().width();
var percent = Math.floor(100 * width / parentWidth);
if (percent > 100) percent = 100;
pos.html(percent + "%");
}
function mouseup() {
$document.unbind('mousemove', mousemove);
}
},
template: "<div id ='container' ng-style=\"{'width':width, 'border':'3px solid black', 'overflow':'hidden'}\">\
<div id='sidebar' ng-style=\"{'width':percent,'height':height, \
'background-color':barColor, 'overflow-y':'hidden'}\">\
<span class='position' ng-style=\"{'overflow':'hidden'}\">{{percent}} </span>\
<div class='dragbar' ng-style=\"{'width':'3px','height':'100%', \
'background-color':'black', 'float':'right', 'cursor':'col-resize'}\"></div>\
</div>\
</div>",
replace: true
}
});
var app = angular.module('DraggableBar', ['components']);