cobuild-angular-stack
Version:
Base stack angular sass jade gulp
97 lines (85 loc) • 4.09 kB
JavaScript
/**
* Created by garusis on 19/06/16.
*/
(function (module) {
module
.directive('sortableTab', ['$timeout', '$document', function ($timeout, $document) {
return {
link: function (scope, element, attrs) {
// Attempt to integrate with ngRepeat
// https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js#L362
var match = attrs.ngRepeat.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
if (!match || !match[2]) return;
var collection = match[2];
var tabs;
scope.$watch(collection, function (newTabs) {
tabs = newTabs;
});
var index = scope.$index;
scope.$watch('$index', function (newIndex) {
index = newIndex;
});
attrs.$set('draggable', true);
// Wrapped in $apply so Angular reacts to changes
var wrappedListeners = {
// On item being dragged
dragstart: function (e) {
e = e.originalEvent;
e.dataTransfer.effectAllowed = 'move';
e.dataTransfer.dropEffect = 'move';
e.dataTransfer.setData('application/json', index);
element.addClass('dragging');
},
dragend: function (e) {
element.removeClass('dragging');
},
// On item being dragged over / dropped onto
dragenter: function (e) {
},
dragleave: function (e) {
element.removeClass('dragover');
},
drop: function (e) {
e = e.originalEvent;
e.preventDefault();
e.stopPropagation();
var sourceIndex = e.dataTransfer.getData('application/json');
scope.$emit('sortableTabs::reorder',{currentPosition:sourceIndex, newPosition:index});
move(sourceIndex, index);
element.removeClass('dragover');
}
};
// For performance purposes, do not
// call $apply for these
var unwrappedListeners = {
dragover: function (e) {
e.preventDefault();
element.addClass('dragover');
},
/* Use .hover instead of :hover. :hover doesn't play well with
moving DOM from under mouse when hovered */
mouseenter: function () {
},
mouseleave: function () {
}
};
angular.forEach(wrappedListeners, function (listener, event) {
element.on(event, wrap(listener));
});
angular.forEach(unwrappedListeners, function (listener, event) {
element.on(event, listener);
});
function wrap(fn) {
return function (e) {
scope.$apply(function () {
fn(e);
});
};
}
function move(fromIndex, toIndex) {
tabs.splice(toIndex, 0, tabs.splice(fromIndex, 1)[0]);
}
}
}
}]);
})(angular.module('uib-util.sortable-tabs'));