[英]$timeout use inside AngularJS factory
我使用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的新手,有人可以幫幫我嗎? 謝謝。
執行上下文this
時候$超時被執行的變化。 您需要保留MODELA this
在$超時(this.counterFunction.bind(本),1000)。 您將this
綁定並傳遞到this.counterFunction,因此counterFunction有權訪問this.progress。
在此處查看有關this
問題的更多信息。 $超時是window.setTimeout包裝https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout#The_this_problem
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.