My goal is to set up a reusable alert service that can be easily called from anywhere in my application with just:
alertService.showAlert('warning', 'something went wrong!');
One example of where I want to use this is after an AJAX call to a backend API. Currently, I am using a factory and a directive for this purpose. However, it seems like something is not working correctly because the directive does not update after calling the showAlert method. Here's a simplified version of what I have so far:
var srv = angular.module('srv', []);
srv.factory('alertService', ['$timeout', function($timeout){
var alertService = this;
alertService.alertNeeded = false;
alertService.alertClass = '';
alertService.alertMessage = '';
alertService.setAlertNeeded = function(){
alertService.alertNeeded = true
};
alertService.setAlertClass = function(type){
if(type === 'warning')
alertService.alertClass = 'alert-warning';
if(type === 'success')
alertService.alertClass = 'alert-success';
if(type === 'info')
alertService.alertClass = 'alert-info';
if(type === 'danger')
alertService.alertClass = 'alert-danger';
};
alertService.setAlertMessage = function(message){
alertService.alertMessage = message;
};
return {
showAlert: function(class, msg){
alertService.setAlertNeeded();
alertService.setAlertClass(class);
alertService.setAlertMessage(msg);
}
};
}]).
directive('myAlerts', ['alertService', function(alertService){
return {
restrict: 'A',
template: '<div ng-class="alertClass" ng-show="alertNeeded">{{alertMessage}}</div>',
link: function(scope){
scope.alertNeeded = alertService.alertNeeded;
scope.alertMessage = alertService.alertMessage;
scope.alertClass = alertService.alertClass;
}
}
}]).
controller('alertShowingController', ['$scope', 'alertService', function($scope, alertService){
alertService.showAlert('warning', 'Warning alert!!!')
}]);
Although my code is slightly different, the concept remains the same - I want to trigger alertService.showAlert(...)
from another controller in a different module (which depends on the srv module) to update the variables in the myAlerts
directive and display the correct alert.
The issue I'm facing is that after calling the showAlert method, the values are set properly, but within the directive code, I'm receiving alertService.alertNeeded
as undefined
.
I am new to AngularJS, so there might be something fundamental that I am missing. I've spent a lot of time trying to figure it out, but I haven't found a solution yet.
Please provide some guidance!