axelav
axelav

Reputation: 435

Refer to Angularjs factory object within the factory

Is it possible to consistently refer to the factory object from within an Angularjs factory? For example, I have an factory Alerts that is made up of an array of alerts, a create method & a dismiss method. Alerts.create() pushes an alert in the Alerts.alerts array & takes an optional parameter that auto-dismisses the array after 5 seconds. Sometimes this works fine, but this sometimes refers to the factory object, sometimes to the global window object. I've also tried setting var self = this, but that also only sometimes works. Code below:

angular.module('services.alerts', [])

.factory('Alerts', function($timeout) {
  return {

    alerts: [],

    create: function(type, msg, close) {
      var newIndex; 

      if (close == null) {
        close = true;
      }

      newIndex = this.alerts.push({
        type: type,
        msg: msg
      }) - 1;

      if (close) {
        $timeout(function() {
          this.dismiss(newIndex);
        }, 5000);
      }
    },

    dismiss: function(index) {
      this.alerts.splice(index, 1);
    }

  };
});

I'm probably missing something obvious, but any help would be greatly appreciated.

Upvotes: 0

Views: 237

Answers (1)

Dennis Traub
Dennis Traub

Reputation: 51644

Try defining the alerts and the accompanying functions inside the function body and then export them.

angular.module('services.alerts', [])
    .factory('Alerts', function($timeout) {
        var alerts = [];

        function create(type, msg, close) {
            ...
            newIndex = alerts.push(...) - 1;

            if (close) {
                $timeout(function() { dismiss(newIndex); }, 5000);
            }
        }

        function dismiss(index) {
            alerts.splice(index, 1);
        }

        return {
            alerts: alerts,
            create: create,
            dismiss: dismiss
        };
    });

Upvotes: 1

Related Questions