Skip to content

Instantly share code, notes, and snippets.

@jonaszuberbuehler
Created April 20, 2016 14:27
Show Gist options
  • Save jonaszuberbuehler/f9dcd33cb6ad3a6b2860dd2ae80a7a6c to your computer and use it in GitHub Desktop.
Save jonaszuberbuehler/f9dcd33cb6ad3a6b2860dd2ae80a7a6c to your computer and use it in GitHub Desktop.
angular material service to stack multiple toasts (demo at https://codepen.io/z00bs/pen/vGrjvX)
(function () {
'use strict';
angular
.module('app')
.service('Notification', Notification);
Notification.$inject = ['$mdToast', '$timeout'];
function Notification($mdToast, $timeout) {
var stack = [];
var debounce;
var lastMsg;
var cooldown = 500;
var service = {};
service.show = show;
return service;
function show(options) {
hideDelay(options, 5000);
internalShow(basicToast(options));
}
function hideDelay(options, delay) {
if (options.hideDelay == undefined) {
options.hideDelay = delay;
}
}
/**
* We defer the showing in case too many toast are created in too little time (seems to be an issue with ng-material).
*
* @param toast
*/
function internalShow(toast) {
(function () {
if (lastMsg === toast.locals.message) {
$timeout.cancel(debounce);
}
lastMsg = toast.locals.message;
debounce = $timeout(function () {
lastMsg = null;
// we stack toasts with different msg not showing within 500 millis (cooldown)
stack.push(toast);
if (stack.length === 1) {
showStacked();
}
}, cooldown);
})();
}
function showStacked() {
if (!stack.length) {
return;
}
var toast = stack[0];
$mdToast.show(toast).then(function () {
stack.shift();
showStacked();
});
}
function basicToast(options) {
return {
templateUrl: 'toast-template.tpl.html',
controller: 'ToastController',
controllerAs: 'vm',
locals: {
message: options.message
},
position: 'top right',
hideDelay: options.hideDelay
};
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment