Angular: Alerts 2

by Roman

HTML

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.no-icons.min.css">
<input type="button" value="info" ng-click="Alerts.info('hello')" />
<input type="button" value="error" ng-click="Alerts.error('hello')" />

CSS

.alerts {
    position: fixed;
    top: 0;
    right: 0;
}

.alert {
    cursor: pointer;
}

JavaScript

angular.module('app', [])

.factory('Alerts', function($timeout, $compile, $rootScope, $document){
    var Alerts = {};
    
    Alerts.messages = [];
    
    var addMessage = function(msgText, type){
        var msg = {text: msgText, type: type};
        Alerts.messages.push(msg);
        $timeout(function(){
            Alerts.remove(msg);
        }, 5000);
    };
    
    Alerts.error = function(msg){
        addMessage(msg, 'error');
    };
    
    Alerts.info = function(msg){
        addMessage(msg, 'info');
    };
    
    Alerts.remove = function(alert) {
        Alerts.messages.splice(Alerts.messages.indexOf(alert), 1);
    }
    
    var scope = $rootScope.$new();
    var alertsElem = angular.element(
        '<div class="alerts">' +
            '<div class="alert alert-{{alert.type}}" ng-repeat="alert in Alerts.messages" ng-click="Alerts.remove(alert)">' +
                '{{alert.text}}' +
            '</div>' +
        '</div>'
    );
    $document.find('body').append(alertsElem);
    $compile(alertsElem)(scope);
    $rootScope.Alerts = Alerts;
    
    return Alerts;
})

.run(function(Alerts){});