This misses out on the extended functionality but gets around the necessity of polluting the rootscope. Anywhere in the app you can plop down the directive <my-alert-display> to get the current list.
Directive:
angular.module('myApp')
.directive('myAlertDisplay', ['alertService', function (alertService) {
return {
restrict: 'AE',
template: '<div ng-repeat="alert in vm.alerts" class="alert alert-{{alert.type}}" role="alert"><button ng-click="vm.closeAlert($index)" type="button" class="close" aria-label="Close"><span aria-hidden="true">×</span></button>{{alert.msg}}</div>',
controller: function(){
var vm = this;
vm.alertService = alertService;
vm.alerts = vm.alertService.alerts;
vm.closeAlert = function (index) {
vm.alertService.closeAlert(index);
}
},
controllerAs: 'vm'
}
}]);
Service:
angular.module('myApp')
.factory('alertService', function () {
var alertService = {};
// create an array of alerts
alertService.alerts = [];
alertService.add = function (type, msg) {
alertService.alerts.push({ 'type': type, 'msg': msg });
};
alertService.closeAlert = function (index) {
alertService.alerts.splice(index, 1);
};
return alertService;
});
This misses out on the extended functionality but gets around the necessity of polluting the rootscope. Anywhere in the app you can plop down the directive <my-alert-display> to get the current list.
Directive:
Service: