This service/directive pair provides a global user alerting mechanism without polluting $rootScope.
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); |