I have an angular service to manage my on screen alerts:
angular.module('theapp')
.factory('Alerts', function ($timeout) {
var unsetMsg = null;
return {
alertType: null,
alertTitle: null,
alertMessage: null,
setMessage: function(type, title, message, timed) {
var self = this;
$timeout.cancel(unsetMsg);
self.alertType = type;
self.alertTitle = title;
self.alertMessage = message;
if (timed)
{
unsetMsg = $timeout(self.unsetMessage,5000);
}
},
unsetMessage: function() {
this.alertType = null;
this.alertTitle = null;
this.alertMessage = null;
$timeout.cancel(unsetMsg);
}
}
});
Setting the message works fine (called from an angular controller) and sets the timeout variable OK, but when the function called within the timeout (unsetMessage) runs after the 5 second delay, the code throws an error this is undefined. Why would it not recognise itself as an object and how do I achieve what I'm trying to do?
One possibility is to use the captured self and apply it on the callback so that the proper context is being passed:
if (timed) {
unsetMsg = $timeout(function() {
self.unsetMessage.apply(self);
}, 5000);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With