Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"this" (object) is undefined when calling angularjs function with $timeout

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?

like image 499
Ben Drury Avatar asked May 18 '26 09:05

Ben Drury


1 Answers

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);
}
like image 168
Darin Dimitrov Avatar answered May 21 '26 00:05

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!