将参数传递给AngularJS $timeout

5

我正在开发一个ionic移动应用程序,需要将参数传递给$timeout promise,以便进行一些操作。我阅读了关于$timeout的angularjs文档(https://docs.angularjs.org/api/ng/service/$timeout),其中提到最后一个参数可以是传递给timeout函数的参数。我尝试了以下方法:

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

但是它没有起作用,我无法在超时函数内访问params变量。我做错了什么吗?还是有其他方法可以做到这一点?谢谢。
2个回答

8
那是一个新的参数,已经随 angular 1.4.x 一起introduced。所以如果你正在尝试在 angular 1.3 或更低版本 中使用它,可能是不可行的。 示例 只要使用正确版本的 angular,您的示例应该可以正常工作。
 $timeout(function(p){
    console.log(p.a);
 },0, true, {a:1, b:2});

另外需要注意的是,您没有将此作为参数传递给超时承诺,它们只是传递给由$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
 });

如果你真正的意图是将参数传递给版本小于1.4的函数中,那么只需将其移动到一个函数中并调用:
 function callIt(params){
    return $timeout(function(){ //Return promise if needed
       //Access params here from the outer closure of the function.
     })
 }

并且只需调用:

callIt({a:1, b:2});

好的,我看到Ionic使用v1.3.6,所以我决定编写这个函数,谢谢。 - oware
@oware 啊,可能你正在使用带有1.3.x的Ionic捆绑包。 - PSL

3

你正在尝试使用的参数是在angularjs 1.4版本中引入的,该版本目前被认为是不稳定的(很可能你正在使用版本<= 1.3 - $timeout文档)。

你可以尝试:

function makeHandler(handler, params) {
  return function() {
    handler(params);
  };
}

$timeout(makeHandler(function(params) {
  alert(params.p1 + " - " + params.p2);
}, {p1 : "Hello", p2 : "World"}), 5000);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接