簡體   English   中英

在AngularJS工廠中使用$ timeout

[英]$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的新手,有人可以幫幫我嗎? 謝謝。

$timeout調用的函數中的this對象,即this.counterFunciton不是ModelA實例,因此應改用$timeout(this.counterFunction.bind(this), 1000)

您可以閱讀有關在JavaScript中綁定this對象的文章

一個有效的Codepen供您參考。

執行上下文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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM