【发布时间】:2016-09-10 02:23:29
【问题描述】:
我使用 AngularJS 工厂为我的项目创建了新的实例模型,每个模型都包含一个进度值,该值将根据“开始”、“暂停”和“停止”用户进行递增、暂停和设置回 0行动。
app.factory('ModelA', ['$timeout', function($timeout) {
function ModelA(progress) {
this.progress = progress;
};
ModelA.prototype = {
startProgress: function() {
this.counterFunction();
},
counterFunction: function() {
this.progress++;
if(this.progress == 100) {
this.progress = 0;
}
//console.log(this.progress);
//console.log(this.counterFunction);
progressTimeout = $timeout(this.counterFunction, 1000);
},
// Haven't tested the method below
pauseProgress: function() {
$timeout.cancel(progressTimeout);
},
stopProgress: function() {
$timeout.cancel(progressTimeout);
this.progress = 0;
}
};
return ModelA;
}]);
由于某种原因,当我在ng-click表达式函数中调用startProgress()时,进度会增加1然后停止。我添加了日志以检查每个呼叫的this.counterFunction。我意识到它只会在第一次打印出1 和整个counterFunction。至于第二次,this.progress 将变为NaN,counterFunction 将显示undefined。
我是 AngularJS 的新手,有人可以帮帮我吗?谢谢。
【问题讨论】:
-
如果以后有人遇到此问题,我建议您查看@BrianHsu 和 Lihau Tan 发布的两个答案,以帮助您更好地理解
setTime和this主题。
标签: javascript angularjs factory