Skip to content

Instantly share code, notes, and snippets.

@wgallios
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save wgallios/d212d32fc24e6ca0b55f to your computer and use it in GitHub Desktop.

Select an option

Save wgallios/d212d32fc24e6ca0b55f to your computer and use it in GitHub Desktop.
Angular.js service to manage alerts - used primarily with ui.bootstrap
/**
* Author: William Gallios <[email protected]>
*
* License: MIT
*
* @param msg - Alert Message
* @param type (optional) - warning|success|danger|info
* @param header (optional) - header of alert
*
* Usage: alertsManager.addAlert('You're doing a great yob!', 'success', 'Wow!');
*
*
*/
app.factory('alertsManager', function ($rootScope, $log) {
return {
alerts: [],
addAlert: function(msg, type, header)
{
if (msg === undefined) return false;
if (type === undefined) type = 'warning';
type = type.toLowerCase();
if (header === undefined)
{
if (type === 'warning') header = 'Warning';
if (type === 'success') header = 'Success';
if (type === 'danger' || type == 'error') header = 'Error';
if (type === 'info') header = "Information";
}
var $index = this.alerts.push({
header: header,
type: type,
msg: msg
}) - 1;
var alert = this.alerts[$index];
var timeout = this.setClearTimeout(alert);
this.alerts[$index].timeout = timeout;
return true;
},
removeAlert: function (alert)
{
var self = this;
var $index = self.alerts.indexOf(alert);
clearTimeout(self.alerts[$index].timeout);
self.alerts.splice($index, 1);
$rootScope.$apply();
},
clearAlerts: function ()
{
var self = this;
angular.forEach(self.alerts, function (alert, k) {
self.removeAlert(k);
});
},
setClearTimeout: function (alert)
{
var self = this;
var timeout = setTimeout(function(){
self.removeAlert(alert);
}, 3000);
return timeout;
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment