Drag and drop using data attributes

I have a drag and drop with data color attributes, you drag the color and drop it on the desired grid square. However, I want to do it with images, I am confused as to how to do this and how to use the data-image-src = "" attribute correctly.

How to do it right?

This is my html:

<div class="peg col-md-2" x-lvl-draggable="true" data-color="green">Green</div>
<div class="peg col-md-2" x-lvl-draggable="true" data-color="red">Red</div>
<div class="peg col-md-2" x-lvl-draggable="true" data-color="blue">Blue</div>
<div class="peg col-md-2" x-lvl-draggable="true" data-color="black">Black</div>
<div class="peg col-md-2" x-lvl-draggable="true" data-color="grey">Grey</div>

      

My css:

.red {
    background: 
}

.blue {
    background-color: blue;
}
.green {
    background-color: green;
}

.black {
    background-color: black;
    color: white;
}

.grey {
    background-color: grey;
}

      

and this is my JS:

angular
            .module('ddApp', ['lvl.directives.dragdrop']) 
            .controller('ddController', ['$scope' , function($scope){ // function referenced by the drop target
                $scope.dropped = function(dragEl, dropEl) {

                    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);
                    }
                }
            }]);

      

+3


source to share


1 answer


The easiest way to do this is to change the color class to background-image: url (""). This way your controller will assign this image class to the dropped element.



If you need to define multiple image sources by data binding, you can define an attribute attribute source image, such as a data image, and assign that image data value to the original image element.

+1


source







All Articles