Skip to content

Instantly share code, notes, and snippets.

@spikeheap
Last active August 29, 2015 14:17
Show Gist options
  • Save spikeheap/9709d80f14bf63050d6c to your computer and use it in GitHub Desktop.
Save spikeheap/9709d80f14bf63050d6c to your computer and use it in GitHub Desktop.
Angular global user bootstrap alerts

This service/directive pair provides a global user alerting mechanism without polluting $rootScope.

Prerequisites

The directive relies on Angular Bootstrap, but you could easily swap this out for a home-rolled alerts setup.

; (function (angular) {
'use strict';
angular
.module('pageAlerts', ['ui.bootstrap','ui.bootstrap.tpls'])
}(window.angular));
<div>
<alert ng-repeat="alert in alerts" type="{{alert.type}}" close="alert.close()">{{alert.message}}</alert>
</div>
; (function (angular) {
'use strict';
angular
.module('pageAlerts')
.directive('pageAlerts', ['PageAlertsService', function(PageAlertsService) {
return {
templateUrl: '/directives/PageAlerts/PageAlerts.html',
replace: true,
link: function (scope) {
scope.alerts = PageAlertsService.alerts;
}
}
}]);
}(window.angular));
; (function (angular) {
'use strict';
angular
.module('pageAlerts')
.factory('PageAlertsService', [ '$timeout', function($timeout) {
// Private functions and internal state
var internal = {
alerts: [],
addAlert: function(type, message, autoClose) {
var newAlert = {
type: type,
message: message,
close: function() { internal.removeAlert(this) }
};
internal.alerts.push( newAlert );
if(autoClose){
$timeout(function() { newAlert.close() }, 5000)
}
},
removeAlert: function(alert) {
internal.alerts.splice( internal.alerts.indexOf(alert), 1);
}
};
// Return the public API for the service
// We'll expose the `alerts` array for convenience
return {
addError: function(message, autoClose) {
internal.addAlert('danger', message, autoClose);
},
addWarning: function(message, autoClose) {
internal.addAlert('warning', message, autoClose);
},
addSuccess: function(message, autoClose) {
internal.addAlert('success', message, autoClose);
},
alerts: internal.alerts
};
} ])
})(window.angular);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment