Skip to content

Instantly share code, notes, and snippets.

@ydaniv
Last active December 30, 2015 00:09
Show Gist options
  • Save ydaniv/7748060 to your computer and use it in GitHub Desktop.
Save ydaniv/7748060 to your computer and use it in GitHub Desktop.
AngularJS-SpinJS SpinButton module
define([
'spin'
], function (Spinner) {
return [
function () {
return {
restrict: 'A',
scope : {
spinAction : '&spinAction',
spinEmit : '@',
spinTrigger: '@'
},
link : function (scope, element, attrs) {
var defaults = {
lines : 40, // The number of lines to draw
length : 0, // The length of each line
width : 4, // The line thickness
radius : 6, // The radius of the inner circle
corners : 1, // Corner roundness (0..1)
rotate : 0, // The rotation offset
direction: 1, // 1: clockwise, -1: counterclockwise
color : '#fff', // #rgb or #rrggbb or array of colors
speed : 1, // Rounds per second
trail : 50, // Afterglow percentage
shadow : false, // Whether to render a shadow
hwaccel : false, // Whether to use hardware acceleration
className: 'spinner', // The CSS class to assign to the spinner
zIndex : 2e9, // The z-index (defaults to 2000000000)
top : 'auto', // Top position relative to parent in px
left : 'auto' // Left position relative to parent in px
},
spinning = false,
action = scope.spinAction,
spinOff = function () {
element.trigger('spinOff');
},
config = Object.create(defaults),
spinner, d, attr;
for ( d in defaults ) {
attr = 'spin' + d[0].toUpperCase() + d.slice(1);
if ( attr in attrs ) {
config[d] = attrs[attr];
}
}
element.on({
click : function (event) {
if ( !spinning ) {
var res = action();
if ( res && typeof res.then == 'function' ) {
element.trigger('spinOn');
res.finally(spinOff);
if ( 'spinEmit' in attrs ) {
scope.$emit(attrs.spinEmit || 'click', res);
}
else if ( 'spinTrigger' in attrs ) {
element.trigger(attrs.spinTrigger, res);
}
}
}
else {
event.preventDefault();
}
},
spinOn : function () {
if ( !spinner ) {
var el = element[0];
if ( /input/i.test(el.tagName) ) {
el = el.parentNode;
}
element.prop('disabled', true)
.attr('disabled', true);
spinning = true;
spinner = new Spinner(config).spin(el);
}
},
spinOff: function () {
if ( spinner ) {
spinner.stop();
spinner = null;
spinning = false;
element.prop('disabled', false)
.attr('disabled', false);
}
}
});
}
};
}
];
});
define([
'angular',
'modules/spin-button/directives'
], function (angular, directives) {
return angular.module('spinButton', [])
.directive('spinButton', directives);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment