gpt4 book ai didi

javascript - 如何在 AngularJS 中使用 $timeout 运行带参数的函数?

转载 作者:行者123 更新时间:2023-12-03 02:32:32 25 4
gpt4 key购买 nike

我的 AngularJS Controller 中有这个函数。看起来像这样;

polling_interval=1000;
var poll = function()
{
//Execution code
$timeout(poll, polling_interval);
};
poll();

它使用 AngularJS 中的 $timeout 服务来不断调用自身。直到我想向此 poll 函数添加参数之前,这一直有效。对于添加的参数,我的代码如下所示;

polling_interval=1000;
var poll = function(param1, param2)
{
//Execution code
$timeout(poll(param1, param2), polling_interval);
};
poll(param1, param2);

语法 Not Acceptable ,我现在不知所措。如何在 AngularJS 中使用 $timeout 执行带参数的函数?如果无法做到这一点,是否有解决此问题的方法?我想让我的 poll 函数接受参数。

最佳答案

$timeout 是 Angular 的 window.setTimeout 包装器。当然,就像 setTimeout 一样,它支持向超时 fn 传递附加参数。

来自 AngularJS API:

$timeout([fn], [delay], [invokeApply], [Pass]);

[fn](函数)是你的函数
[延迟](数字)延迟(以毫秒为单位)
[invokeApply]( bool 值)默认为 true,如果为 true,则 fn 在 $apply 内运行,如果为 false,则跳过模型脏检查。
[通过]附加参数!这就是你想要的!

你的代码应该是什么样子:

polling_interval = 1000;
var poll = function(param1, param2){
//Execution code
$timeout(poll, polling_interval, true, param1, param2);
};
poll(param1, param2);

这是将参数传递给超时 fn 的正确方法。我希望您觉得这很有用。

编辑:此功能于 2015 年 1 月 22 日 (v1.4.1) 添加,在该版本之前,正确的方法是:

polling_interval = 1000;
var poll = function(param1, param2){
//Execution code
$timeout(poll.bind(null, param1, param2), polling_interval);
};
poll(param1, param2);

关于javascript - 如何在 AngularJS 中使用 $timeout 运行带参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22876031/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com