Part 1 - Utility Code:
var blockLoad =
($timeout, promise, loadingFunction) => {
var
markSystemLoading = $timeout(() => {
loadingFunction(true)},
500)
}
return
promise.finally(() => {
$timeout.cancel(markSystemLoading
)
loadingFunction(false);
})
}
Part 1 - Usage:
blockLoad(promise,
(loading) => {
$scope.isLoading
= loading;
})
This code is pretty simple aspect oriented stuff. You start a timeout since you don't want to flash loading for short waits. I have arbitrarily chosen half a second. The asynchronous promise has a finally condition that will run when it completes and mark the system as not loading. It will additionally cancel the timeout to prevent it from erroneously marking your loading condition to be true. This also returns a promise that chains with the original promise so it fits into code nicely. The usage is simple and flexible.
Part 2 - The Directive
I built this on top of a JQuery control, because I am lazy, but here is a quick directive.
function ($parse, $translate) {
return {
restrict: 'AC',
link: function (scope, lElement, attrs) {
var message = attrs.message;
scope.$watch(attrs.hpBlockOn, function (value) {
if (value) {
lElement.block({
message: message,
overlayCSS: { backgroundColor: '#CCCCCC' },
css: { width: '200px' }
});
} else {
lElement.unblock();
}
});
}
}
}
Part 2 - Usage:
<div hp-block-on="isLoading" message="LOADING">
All this allows blocking of the UI during asynchronous requests to be added with about 4 lines. It handles errors from the requests and prevents flashing loading too soon.
No comments:
Post a Comment