How to run function with parameters using $timeout in AngularJS?

匿名 (未验证) 提交于 2019-12-03 03:04:01

问题:

I have this function inside my AngularJS controller. It looks like this;

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

It uses the $timeout service in AngularJS to keep calling itself. This works until I wanted to add parameters to this poll function. My code looks like this for the parameters added;

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

The syntax was not acceptable and I am at a loss now. How do I execute the function with parameters using $timeout in AngularJS? If this cannot be done, are there work-arounds to this problem? I would like to have my poll function accept parameters.

回答1:

Because the first parameter type of the $timeout is function, you need to do like this:

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


回答2:

$timeout is Angular's wrapper for window.setTimeout. Naturally, just like setTimeout it supports passing additional parameters to the timed-out fn.

From AngularJS API:

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

[fn] (function) being your function
[delay] (number) the delay in ms
[invokeApply] (boolean) defaults to true, on true, the fn is run inside $apply, if false, it skips model dirty checking.
[Pass] additional parameters! This is what you want!

How your code should look like:

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

This is the proper way to pass parameters to a timed-out fn. I hope you find this useful.

EDIT: This feature was added on January 22, 2015 (v1.4.1), prior to that version, the correct approach would have been:

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


回答3:

Using an anonymous function would probably be the easiest way.

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!