是否有可能始终从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);
}
};
});
我可能遗漏了一些显而易见的东西,但任何帮助都会非常感激。
答案 0 :(得分: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
};
});