Skip to content

Instantly share code, notes, and snippets.

@homerjam
Last active September 14, 2021 11:06
Show Gist options
  • Save homerjam/aec5bb1c68a3bfb0ae95c1b83344a4cf to your computer and use it in GitHub Desktop.
Save homerjam/aec5bb1c68a3bfb0ae95c1b83344a4cf to your computer and use it in GitHub Desktop.
Angular Material draggable chips directive
angular.module('mdChipDraggable', [])
.directive('mdChipDraggable', function () {
return {
restrict: 'A',
scope: {},
bindToController: true,
controllerAs: 'vm',
controller: ['$document', '$scope', '$element', '$timeout',
function ($document, $scope, $element, $timeout) {
var vm = this;
var options = {
axis: 'horizontal',
};
var handle = $element[0];
var draggingClassName = 'dragging';
var droppingClassName = 'dropping';
var droppingBeforeClassName = 'dropping--before';
var droppingAfterClassName = 'dropping--after';
var dragging = false;
var preventDrag = false;
var dropPosition;
var dropTimeout;
var move = function (from, to) {
this.splice(to, 0, this.splice(from, 1)[0]);
};
$element = angular.element($element[0].closest('md-chip'));
$element.attr('draggable', true);
$element.on('mousedown', function (event) {
if (event.target !== handle) {
preventDrag = true;
}
});
$document.on('mouseup', function () {
preventDrag = false;
});
$element.on('dragstart', function (event) {
if (preventDrag) {
event.preventDefault();
} else {
dragging = true;
$element.addClass(draggingClassName);
var dataTransfer = event.dataTransfer || event.originalEvent.dataTransfer;
dataTransfer.effectAllowed = 'copyMove';
dataTransfer.dropEffect = 'move';
dataTransfer.setData('text/plain', $scope.$parent.$mdChipsCtrl.items.indexOf($scope.$parent.$chip));
}
});
$element.on('dragend', function () {
dragging = false;
$element.removeClass(draggingClassName);
});
var dragOverHandler = function (event) {
if (dragging) {
return;
}
event.preventDefault();
var bounds = $element[0].getBoundingClientRect();
var props = {
width: bounds.right - bounds.left,
height: bounds.bottom - bounds.top,
x: (event.originalEvent || event).clientX - bounds.left,
y: (event.originalEvent || event).clientY - bounds.top,
};
var offset = options.axis === 'vertical' ? props.y : props.x;
var midPoint = (options.axis === 'vertical' ? props.height : props.width) / 2;
$element.addClass(droppingClassName);
if (offset < midPoint) {
dropPosition = 'before';
$element.removeClass(droppingAfterClassName);
$element.addClass(droppingBeforeClassName);
} else {
dropPosition = 'after';
$element.removeClass(droppingBeforeClassName);
$element.addClass(droppingAfterClassName);
}
};
var dropHandler = function (event) {
event.preventDefault();
var droppedItemIndex = parseInt((event.dataTransfer || event.originalEvent.dataTransfer).getData('text/plain'), 10);
var currentIndex = $scope.$parent.$mdChipsCtrl.items.indexOf($scope.$parent.$chip);
var newIndex = null;
if (dropPosition === 'before') {
if (droppedItemIndex < currentIndex) {
newIndex = currentIndex - 1;
} else {
newIndex = currentIndex;
}
} else {
if (droppedItemIndex < currentIndex) {
newIndex = currentIndex;
} else {
newIndex = currentIndex + 1;
}
}
// prevent event firing multiple times in firefox
$timeout.cancel(dropTimeout);
dropTimeout = $timeout(function () {
dropPosition = null;
move.apply($scope.$parent.$mdChipsCtrl.items, [droppedItemIndex, newIndex]);
$scope.$apply(function () {
$scope.$emit('mdChipDraggable:change', {
collection: $scope.$parent.$mdChipsCtrl.items,
item: $scope.$parent.$mdChipsCtrl.items[droppedItemIndex],
from: droppedItemIndex,
to: newIndex,
});
});
$element.removeClass(droppingClassName);
$element.removeClass(droppingBeforeClassName);
$element.removeClass(droppingAfterClassName);
$element.off('drop', dropHandler);
}, 1000 / 16);
};
$element.on('dragenter', function () {
if (dragging) {
return;
}
$element.off('dragover', dragOverHandler);
$element.off('drop', dropHandler);
$element.on('dragover', dragOverHandler);
$element.on('drop', dropHandler);
});
$element.on('dragleave', function (event) {
$element.removeClass(droppingClassName);
$element.removeClass(droppingBeforeClassName);
$element.removeClass(droppingAfterClassName);
});
}],
};
});
@homerjam
Copy link
Author

homerjam commented Apr 3, 2016

Example usage:

<md-chips ng-model="ctrl.fruitNames">
    <md-chip-template>
        <div md-chip-draggable>{{$chip}}</div>
    </md-chip-template>
</md-chips>

@sinedsem
Copy link

sinedsem commented Apr 4, 2016

Hi! Can I see demo somewhere?

@homerjam
Copy link
Author

homerjam commented Apr 5, 2016

@alisonmsmith
Copy link

Works great! FYI, at line 130, I think you want to use the new index instead of the original index to retrieve the item:

item: $scope.$parent.$mdChipsCtrl.items[newIndex],

@lumalav
Copy link

lumalav commented Jun 21, 2016

Pretty cool @homerjam.
Another suggestion is to stop the dragging if the number of chips equals to one. If you don't do it, you add a 0 after the chip.

I did it by adding: if($scope.$parent.$mdChipsCtrl.items.length == 1) return; to the dragstart event

@alisonmsmith
Copy link

alisonmsmith commented Sep 28, 2016

@lumalav - the issue that you note is actually because of dragging into the 'input' area instead of the chip list. You can see the issue in the codepen if you drop any of the three chips into the input area beyond the chip list. The index is added (hence why you see 0 when you drag the first chip) and the chip remains in its original location.

A better fix is to prohibit dropping into the chip input area. I don't know the best way to do this, but here's what I hacked into the dragstart event:

var input = $element.parent().children('_md-chip-input-container').children('div').children('input');
angular.element(input).off('drop'
angular.element(input).on('drop', function(event) {
    event.preventDefault();
});

Also, instead of just ignoring the drop, you may want to add the element to the end of the list if that's likely the user intent.

@pedraldo
Copy link

@alisonmsmith
I totally agree with your hack. But I think you missed that with $element, you're using JQLite and not jQuery.
So you can't do all DOM manipulation and navigation that you can do with jQuery (unfortunately).
See here : https://docs.angularjs.org/api/ng/function/angular.element

In this case, you can't specify a selector to the children function, therefore you're not targetting the right element.
I tried few things and here is what I did (always in dragstart event function) :

var chipWrapperChildren = $element.parent().children();
if (chipWrapperChildren.length > 0) {
    var inputContainer = angular.element(chipWrapperChildren[chipWrapperChildren.length-1]);
    var input = inputContainer.children()[0];
                         
    angular.element(input).off('drop');
    angular.element(input).on('drop', function(event) {
        event.preventDefault();
    });
}

Surely not the most beautiful code but it does the job !

@lebinio
Copy link

lebinio commented Oct 19, 2017

Can I use it for my project? Are there any restrict to use it?
Please add license, thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment