Skip to content

Instantly share code, notes, and snippets.

@niaher
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niaher/8b7925c2584182127f53 to your computer and use it in GitHub Desktop.
Save niaher/8b7925c2584182127f53 to your computer and use it in GitHub Desktop.
Angular directive for Ladda (http://lab.hakim.se/ladda/). There are other variations, but this one provides the automatic progress increment which looks natural.
// https://gist.github.com/niaher/8b7925c2584182127f53
'use strict';
angular.module('ui.ladda', []).directive('laddaButton', ["$q", function ($q) {
function run(ladda) {
ladda.start();
var progress = 0;
var timeout = null;
function increment(currentProgress) {
if (currentProgress >= 1) {
return 1;
}
var random;
if (currentProgress >= 0 && currentProgress < 0.25) {
// Start out between 3 - 6% increments
random = (Math.random() * 3 + 3) / 100;
} else if (currentProgress >= 0.25 && currentProgress < 0.65) {
// increment between 0 - 3%
random = (Math.random() * 3) / 100;
} else if (currentProgress >= 0.65 && currentProgress < 0.9) {
// increment between 0 - 2%
random = (Math.random() * 2) / 100;
} else if (currentProgress >= 0.9 && currentProgress < 0.99) {
// finally, increment it .5 %
random = 0.005;
} else {
// after 99%, don't increment:
random = 0;
}
return currentProgress + random;
}
function go() {
timeout = setTimeout(function () {
progress = increment(progress);
ladda.setProgress(progress);
if (progress < 1) {
go();
} else {
stop(250);
}
}, 250);
}
function stop(delay) {
var deferred = $q.defer();
clearTimeout(timeout);
ladda.setProgress(1);
if (typeof delay == "number") {
setTimeout(function () {
ladda.stop();
deferred.resolve();
}, delay);
} else {
ladda.stop();
deferred.resolve();
}
return deferred.promise;
}
go();
return {
stop: stop
};
}
return {
restrict: "C",
scope: {
promise: "=uiLaddaPromise",
},
link: function (scope, element, attrs) {
if (!attrs.dataStyle) attrs.$set("data-style", "expand-right");
if (!attrs.dataSpinnerSize) attrs.$set("data-spinner-size", "30");
if (!attrs.dataSpinnerSize && element.hasClass("btn-default")) attrs.$set("data-spinner-color", "gray");
var ladda = window.Ladda.create(element[0]);
var runner = null;
function start() {
if (runner != null) {
runner.stop();
}
runner = run(ladda);
};
function stop() {
if (runner != null) {
runner.stop(220);
}
}
scope.$watch(function() {
return (scope.promise || {}).$promise;
}, function (newValue, oldValue) {
if (newValue == oldValue || newValue == null) return;
if (typeof (newValue) == "boolean") {
if (newValue == true) {
start();
} else {
stop();
}
}
else { // If it's a promise.
start();
newValue.then(stop, stop).then(function () {
scope.promise.$promise = null;
});
}
});
}
};
}]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment