Generic alerts are a common requirement in most web applications, and as your Angular application grows in complexity the importance of a standardised way of feeding back to the user gains importance with it. Luckily it’s quite straightforward to leverage Angular services as a system-wide alerting tool.
There are a number of articles covering Angular user alerting, but each one relied on
Th first problem we need to solve is to collect and manage the list of alerts. to do this we can create a very simple Angular service:
We can then create a directive to interact with the service:
The above example uses Angular Bootstrap alerts, but you can obviously roll your own within the directive.
To add the alerts to your page all you need is
The service/directive pair results in a globally accessible alerting service without the need to pollute the
$rootScope. One criticism of this approach is that the service and directive are tightly coupled, but this can be remedied by passing in the service as an attribute to the directive, an exercise I’ll leave to the reader (but grab me in the comments or on Twitter if you want a hand ;) ).
Was this post useful? Why not help others find it by sharing on twitter. While you're there, get in touch and let me know what you think!