Application notification system with Foundation and Angular

Single Page Applications present some user experience challenges, especially if your target user is used to seeing page refreshes when they perform server actions. The async nature of SPAs hide server calls, so you have to be deliberate about how to communicate activity to your user. Toasts (small popup notifications) provide a subtle but effective way of communicating to your users without distracting them from their activity.

The Foundation for Apps framework provides a neat little toast notification system that is accessible via the FoundationApi service and can be deployed easily across your app. Just include the FoundationApi service in your controllers and use the publish method to trigger the notification.

To trigger the notifications, we will be using Angular’s $rootScope.$broadcast method to create an event based notification system.

The reason we use $rootScope here rather than just $scope is that we want to generalize the message to all scopes, no matter which controller is currently being used. For a clear explanation of the difference, check out this Stack Overflow answer.

Here’s an example of a notification system that fires when a user requests to follow another user.

Include the zurb-notification directive with type and position

We’ll include one notification template for success and one for error.

The id here tells the FoundationApi which HTML element to use as the template. And position will determine where on the screen the notification will appear.

Use the FoundationApi service to publish your notification and wrap the notification call in an event listener

The publish method on the FoundationApi takes an id and an object that specifies the title, content and duration of the toast popup.

We need to let our app know when to trigger the notification. To do this we’ll wrap our publish call in a $scope.$on method that takes an event name and a callback that is triggered when the event is broadcast.

Broadcast the event from a service

Services are where our async operations will live so we need to include a $broadcast at the point at which we want to notify the user of success or error. The $broadcast method takes an event name string, and optional arguments that are returned in the $scope.$on callback. Here we’ll pass in a custom message that will be displayed in the toast popup.

You now have an elegant notification system that is extendable; you can create all sorts of success and error messages that will be passed across your app using Angular’s event system, notifying your users of key events and actions.