FED-icons-01 FED-icons-02 FED-icons-03 FED-icons-04 FED-icons-05 FED-icons-06 FED-icons-07 FED-icons-08 FED-icons-09 FED-icons-10 FED-icons-11

UI Bootstrap's alert message directive is a great module that will take care of displaying all of your application's alert messages. However, I found that it was lacking one important feature - the ability to manage auto-closing of the alerts.

I didn't want my users to always have to manually close the alerts. So, I wrote a simple helper service to add this functionality on top of UI Bootstrap's directive.

First, we have our alert template, which is the standard UI Bootstrap implementation.

<div class="alertContainer">
	<div ng-repeat='alert in alerts track by $index' type='{{alert.type}}' close='closeAlert($index)'> {{alert.msg}} </div>

My idea was to write a service that manages the alert array outside of UI Bootstrap's directive. This way we can customize how long we want alert messages to stick around for, and create a standard method of adding alerts to our array.

You will first notice, this is not in fact a service. In it's current form it is simply an array and some helper functions on rootScope. This is generally not best practice, but this can easily be moved into a service, directive, or whatever works best for your application.

app.run(function ($rootScope, $timeout) {

	$rootScope.alerts = [];

	$rootScope.addAlert = function (alertObj, duration) {
		var newAlertObj = alertObj;
		newAlertObj.uid = Math.floor(Math.random() * 100000);
		var alertIndex;


		if (duration !== 'stay') {
			$timeout(function () {
				for (var i = 0; i < $rootScope.alerts.length; i++) {
					if ($rootScope.alerts[i].uid === newAlertObj.uid) {
						alertIndex = i;
				$rootScope.alerts.splice(alertIndex, 1);
			}, duration || 2500);

	$rootScope.closeAlert = function (index) {
		$rootScope.alerts.splice(index, 1);

The key to this abstraction is adding a unique ID to each alert message so we can then find that alert again in the array when we want to destroy it. When we add an alert to the array, we will define how long we want it to stay on screen for.

// alert will remain on screen default amount of time ... in this case 2.5 seconds
$rootScope.addAlert({type: 'success', msg: 'Please check your email for a confirmation email.'});

// alert will remain on screen 1 second
$rootScope.addAlert({type: 'success', msg: 'Form has been sumbmitted!'}, 1000);

// alert will remain on screen until user closes it manualy
$rootScope.addAlert({type: 'danger', msg: 'Error message!'}, 'stay');

A simple, clean, and easily customizable to manage alert durations, and possibly more.

Front Edge

Lead UI Developer