August 19, 2014

Creating a flexible Alerting Service with AngularJS (Part 1)

Using AngularJS 1.2.20, Bootstrap 3, underscore.js

While working on recent AngularJS project I had to come up with an easier way to deal with application messages (error messages, alert messages, debug messages,etc).

If you have a tiny AngularJS app $scope.error = ‘Error Description’; will do it for sending simple error messages to your controllers, but if you’re using this approach for a larger app you’ll quickly find it’s not a good idea.

While I am sure there are other ways to do this, perhaps better ones, this article will show you how to implement a flexible Alerting/Messaging Service for use in an AngularJS app.

Usage inside Controllers

Why do I have to pass in scope every time?

The way this Message Service works is it allows you to set one message of each type (info,warning,error,success,debug) ,so 5 in total, on any $scope you pass in. This allows you to set scope specific error messages. This is good because you can have a controller that has a warning message, and another one that has an error message. The messages won't interfere with each other.

Usage inside Partials

To make this really easy, I've used bootstrap 3 template code to generate several html templates for the messaging.
You can simply include the following files (messages.tpl.html) and (debug-messages.tpl.html) in your AngularJS application (assuming you are using the bootstrap 3 framework).

The above partials can then be embedded anywhere in your app where you want to display an messages. Typical place would be somewhere on top of your main app content. I like to keep the messages and the debug messages separate like this for easier including where needed. Just make sure they are inside the scope for which you are displaying these messages (otherwise the $scope.messages property will be undefined, and no messages will show for this scope).

So for example, if you are using the controller from before

you should be using this code to add the messages to your app.

How the Message Service actually works

The message service adds a $scope.message property to any $scope for which you invoked the MessageService.init($scope) method. It then keeps track and updates $scope.message any time you call one of the message methods such as MessageService.error($scope,'This is an error');

And here is the actual Message Service (MessageService.js)

If you need the angular and underscore.js libraries used in this example, just add the following to your app

Part 2 - Coming soon ... more complex example, custom error objects, global messages and scope specific messages