将参数传递给AngularJS $ timeout

owa*_*are 5 javascript angularjs ionic-framework

我正在开发一个离子移动应用程序,我需要将参数传递给$ timeout promise,这样我就可以使用该参数进行一些操作.我阅读了有关$ timeout(https://docs.angularjs.org/api/ng/service/ $ timeout)的angularjs文档,它说最后一个参数可以是传递给超时函数的参数.我试过这个:

$timeout(function(params){
    alert(params.p1 + " - " + params.p2);
}, 5000, true, {p1 : "Hello", p2 : "World"});
Run Code Online (Sandbox Code Playgroud)

但它不起作用,我无法访问超时函数内的params变量.

难道我做错了什么?或者,还有另一种方法吗?

谢谢

PSL*_*PSL 8

这是一个已经有了新的说法引进角1.4.x中.因此,您可能尝试使用角度为1.3或更小的版本.

如果使用正确版本的角度,您的示例应该可以正常工作.

 $timeout(function(p){
    console.log(p.a);
 },0, true, {a:1, b:2});
Run Code Online (Sandbox Code Playgroud)

另外需要注意的是,您没有将此作为参数传递给超时承诺,它们只是传递给由$timeout服务运行的函数的参数.如果要将参数作为超时承诺解析的值传递,则只返回该值.

 $timeout(function(p){
    return p; //<-- return it
 },0, true, {a:1, b:2})
 .then(function(value){
     console.log(value)//<-- this is same as p
 });
Run Code Online (Sandbox Code Playgroud)

如果您的真实意图是将参数传递给版本<1.4的函数,那么只需将其移动到函数并调用它:

 function callIt(params){
    return $timeout(function(){ //Return promise if needed
       //Access params here from the outer closure of the function.
     })
 }
Run Code Online (Sandbox Code Playgroud)

并致电:

callIt({a:1, b:2});
Run Code Online (Sandbox Code Playgroud)