【发布时间】: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