I’ve been working on a web application using AngularJS and bootstrap.
Most pages have forms that must be validated and user actions to be acknowledged (success/failure).
Bootstrap provides simple way to add alerts for achieve this.
Easiest way to add these alerts dynamically (with AngularJS) is to create a boolean flag in $scope, and use ng-if in html to display the alert.
Though very quickly, these number of validations sky rocket (especially for large forms like register page), and adding a boolean
variable in $scope and creating div tag in html for each validation becomes cumbersome. Also, code becomes too large & lot less readable.
All these alerts can be clubbed into AlertService. Subsequently, all controllers throughout the application can add alerts to respective pages
using that service.
Let’s walk through the solution code.
Step 1: Create AlertService
Create alert service to be used across the application.
The alert service retains all the alerts in rootscope so that all controllers can access alerts array.
It exposes functions add, close and clear for respective actions.
Type = type of bootstrap alert - warning, success, danger etc.
Msg = message to be displayed to the user
Section = section of html page in which you want the alerts to be displayed. More on this later.
On route change success, clear the alerts so that alerts of one page are not displayed on other.
The event to listen for is $stateChangeSuccess (since I am using State Router).
If you are using older router of AngularJS please use $routeChangeSuccess
Note: Please add the file in index.html script tag.
Step 2: HTML code to display alerts
This HTML code snippet uses the ‘alerts’ array from the rootScope, iterates through it using ng-repeat and creates those many alert tags with appropriate class and message.
Notice the filter pipe of the div tag above. It filters out the alerts only for that specific section.
Thus if your page has 2 separate sections for alerts, use second div mentioned above.
In fact you can keep adding sections, but practically 2 should suffice.
Step 3: Create alerts from your controllers or services
Add alerts from your controllers/services
Step 4: Confirm
Thats it. Now in every page you want alerts, just add directive in html and use AlertService in corresponding Controller.
Hit me in the comments if you are stuck implementing this.