$timeout在AngularJS工厂中使用
$timeout use inside AngularJS factory
我使用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
- Angularjs工厂注入错误
- 如何将参数传递到angularJs中的工厂
- AngularJS:$q.dedefe()不能由工厂方法共享
- AngularJS错误:提供程序必须从$get工厂方法返回值
- 如何在AngularJS工厂中正确声明对象属性
- 修复AngularJS错误:提供程序必须从$get工厂方法返回值
- AngularJS控制器在注入工厂时抛出错误
- AngularJS-工厂中promise ID字段的返回值
- AngularJS-我是不是在工厂注射中遗漏了什么
- Http状态代码工厂AngularJs
- angularjs-ui路由器解析工厂未定义
- 在同一工厂中的函数中使用函数并传递$scope(AngularJS)
- AngularJS可重用工厂
- 访问 angularjs 工厂数据之外的承诺
- 如何将数据从 angularJS 工厂填充到控制器
- 在AngularJS建立一个工厂而不是Singleton
- 使用工厂/服务在控制器AngularJS之间推送数组中的数据
- 无法从工厂 AngularJS 中的 JSON 文件中提取数据
- 与工厂AngularJS在控制器之间共享数据
- 使用工厂angularJS设置并获取值