Ben Drury
Ben Drury

Reputation: 1376

Undefined "this" in Angular factory

I have am Angular Factory that creates global on screen alerts, but unsetting the alerts errors with an "TypeError: undefined is not a function" error.

My Factory is:

 'use strict';
angular.module('meanstackStarterApp')
  .factory('Alerts', function ($timeout) {

    var alertType = null;
    var alertTitle = null;
    var alertMessage = null;

    return {
        setMessage: function(type, title, message, timed) {
            console.log("in");
            this.alertType = type;
            this.alertTitle = title;
            this.alertMessage = message;
            if (type == "alert-danger")
            {
                alertMessage = message + alertMessages.alertMessage_GlobalTryAgain;
            }
            if (timed)
            {
                // Set Timeout on unset
                $timeout(this.unsetMessage(),5000);
            }
        },

        unsetMessage: function() {
            console.log("out");
            this.alertType = null;
            this.alertTitle = null;
            this.alertMessage = null;           
        }
    };
  });

The setMessage function works fine but the unsetMessage errors on the this.

If I remove this prefix from the variables, the code runs through without erroring, but does not actually set the factory variables.

What am I missing?

Upvotes: 1

Views: 661

Answers (1)

quicoli
quicoli

Reputation: 622

I have here something like you, I'm changing your code to look like mine:

angular.module('meanstackStarterApp')
  .factory('Alerts', function ($timeout) {
    var self = this;

    var alertType = null;
    var alertTitle = null;
    var alertMessage = null;


    self.setMessage = function(type, title, message, timed) {
            console.log("in");
            self.alertType = type;
            self.alertTitle = title;
            self.alertMessage = message;
            if (type == "alert-danger")
            {
                alertMessage = message + alertMessages.alertMessage_GlobalTryAgain;
            }
            if (timed)
            {
                // Set Timeout on unset
                $timeout(self.unsetMessage(this),5000);
            }
        };

     self.unsetMessage = function() {
            console.log("out");
            self.alertType = null;
            self.alertTitle = null;
            self.alertMessage = null;           
        };

     return self;
  });

Upvotes: 1

Related Questions