$timeout在AngularJS工厂中使用

$timeout use inside AngularJS factory

本文关键字:工厂 AngularJS timeout      更新时间:2023-09-26

我使用AngularJS factory为我的项目创建新的实例模型,每个模型都包含一个进度值,该进度值将根据"start", "pause"answers"stop"用户操作进行递增,暂停和设回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对象的文章。

执行上下文this在执行$timeout时发生变化。您需要在$timeout(this. counterfunction .bind(this), 1000)中保存ModelA this。您将this绑定并传递给它。因此,counterFunction对this.progress.

具有访问权限。

点击这里查看this问题的更多信息。$timeout是window.setTimeout的包装器https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout The_this_problem