Drag and Drop Directives

Simple directives to enable drag and drop in your application

Click and drag a color onto the grid to the right

Green
Red
Blue
Black
Grey

Relevant Html

		
		<!-- include the uuid service as well as the directive -->
		<script src="script/lvl-uuid.js"></script>
		<script src="script/lvl-drag-drop.js"></script>
		
		
		<style>
			.lvl-over {
				/* applied to a drop target when a draggable object is over it */
				border: 2px dashed black !important;
			}

			.lvl-target {
				/* 
				applied to all drop targets when a drag operation begins 
				removed when the drag operation ends
				used to indicate drop targets on a page 
				*/
				background-color: #ddd;
				opacity: .5;
			}

			[draggable] {
				/* not applied by the directive, but useful to indicate a draggable element */
				-moz-user-select: none;
				-khtml-user-select: none;
				-webkit-user-select: none;
				user-select: none;
				cursor: move;
				border:1px solid black;
			}
		</style>

		<div ng-controller="ddController" style="margin-top:50px;">
			<div class="row">
				<div class="col-md-1 col-md-offset-1">
					<p>Click and drag a color onto the grid to the right</p>
					<div class="peg green" x-lvl-draggable="true" data-color="green">Green</div>
					<div class="peg red" x-lvl-draggable="true" data-color="red">Red</div>
					<div class="peg blue" x-lvl-draggable="true" data-color="blue">Blue</div>
					<div class="peg black" x-lvl-draggable="true" data-color="black">Black</div>
					<div class="peg grey" x-lvl-draggable="true" data-color="grey">Grey</div>
				</div>
	
				<div class="col-md-10">
					<div ng-repeat="r in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]">
						<span class="slot circle" ng-repeat="c in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" x-lvl-drop-target="true" x-on-drop="dropped(dragEl, dropEl)"></span>
					</div>
				</div>
			</div>
		</div>
		

Page Script

		angular
			.module('ddApp', ['lvl.directives.dragdrop']) // register the directive with your app module
			.controller('ddController', ['$scope' , function($scope){
				$scope.dropped = function(dragEl, dropEl) { // function referenced by the drop target
					//this is application logic, for the demo we just want to color the grid squares
					//the directive provides a native dom object, wrap with jqlite
					var drop = angular.element(dropEl);
					var drag = angular.element(dragEl);
				
					//clear the previously applied color, if it exists
					var bgClass = drop.attr('data-color');
					if (bgClass) {
						drop.removeClass(bgClass);
					}

					//add the dragged color
					bgClass = drag.attr("data-color");
					drop.addClass(bgClass);
					drop.attr('data-color', bgClass);

					//if element has been dragged from the grid, clear dragged color
					if (drag.attr("x-lvl-drop-target")) {
						drag.removeClass(bgClass);
					}
				}
			}]);