【问题标题】:Refer to Angularjs factory object within the factory参考工厂内的Angularjs工厂对象
【发布时间】:2014-07-29 19:28:20
【问题描述】:

是否可以一致地从 Angularjs 工厂中引用工厂对象?例如,我有一个工厂Alerts,它由一组警报、一个create 方法和一个dismiss 方法组成。 Alerts.create()Alerts.alerts 数组中推送一个警报,并采用一个可选参数,该参数会在 5 秒后自动关闭数组。有时这可以正常工作,但 this 有时指的是工厂对象,有时指的是全局 window 对象。我也尝试过设置var self = this,但这也只是有时有效。代码如下:

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);
    }

  };
});

我可能遗漏了一些明显的东西,但我们将不胜感激。

【问题讨论】:

    标签: javascript angularjs oop factory


    【解决方案1】:

    尝试在函数体内定义alerts 和附带的函数,然后将它们导出。

    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
            };
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-18
      • 1970-01-01
      • 2016-09-07
      • 2011-01-05
      • 1970-01-01
      相关资源
      最近更新 更多