Angular: $rootScope changes.

by jannis

HTML

<script src="http://code.angularjs.org/1.1.5/angular.js"></script>
<div class="notification">
    
    <!-- Modal/Notification Errors -->
    <div ng-cloak ng-show="errors.length" class="notification__modal">
        <div class="notification__item notification__item--{{ error.type }}" ng-repeat="error in errors">
            <div class="notification__inner">
                <div class="notification__content">
                    <p class="notification__message">{{ error.message }}</p>
                </div>
            </div>
        </div>
    </div>
    
</div>

CSS

.notification__item--error { color: red; }
.notification__item--notice { color: blue; }
.notification__item--warning { color: orange; }

JavaScript

var myApp = angular.module('myApp',[]);

// The Error Service.
myApp.factory('Notification', [ '$rootScope', function($rootScope) {
    // initial setup.
    $rootScope.errors = [];
    
    // Factory interface.
    return {
        add: function(message, type) {
            // adds an error message to the $rootScope which should update the UI.
            $rootScope.errors.push( { message: message, type: type } );
        },
        flush: function() {
            // remove all error messages.
            $rootScope.errors = [];
        }
    }
} ]);

// Base Ctrl.
function AppCtrl(Notification) {
    // Create an error.
    Notification.add( 'My first error', 'error' );
    Notification.add( 'My second warning.', 'warning' );
    
    // wait 2s then flush all errors.
    setTimeout( function() {
        Notification.flush();
    } , 2000 );
};