I am developing an ionic mobile application and I need to pass parameters to the $timeout promise so I can make some operations with that parameters. I read the angularjs doc about $timeout (https://docs.angularjs.org/api/ng/service/$timeout) and it says that the last parameter can be parameters passed to the timeout function. I tried this:
$timeout(function(params){
alert(params.p1 + " - " + params.p2);
}, 5000, true, {p1 : "Hello", p2 : "World"});
but it is not working, I can't have acces to the params variable inside the timeout function.
Am I doing something wrong? or, is there another way to do this?
Thanks
That is a new argument that has been introduced with angular 1.4.x. So it could be possible that you are trying to use it with angular 1.3 or lesser version.
Your example should just work provided you are using right version of angular.
$timeout(function(p){
console.log(p.a);
},0, true, {a:1, b:2});
Another thing to note is you are not passing this as argument to the timeout promise, they are just arguments passed to the function run by $timeout
service. If you want to pass the argument as a value resolved by the timeout promise then just return the value.
$timeout(function(p){
return p; //<-- return it
},0, true, {a:1, b:2})
.then(function(value){
console.log(value)//<-- this is same as p
});
If your real intention is to get the argument passed into the function with version < 1.4, then just move it to a function and invoke it:
function callIt(params){
return $timeout(function(){ //Return promise if needed
//Access params here from the outer closure of the function.
})
}
and just call:
callIt({a:1, b:2});
The parameter you're trying to use has been introduced in 1.4 version of angularjs which is currently considered unstable (most likely you're using version <= 1.3 - $timeout docs).
You could try:
function makeHandler(handler, params) {
return function() {
handler(params);
};
}
$timeout(makeHandler(function(params) {
alert(params.p1 + " - " + params.p2);
}, {p1 : "Hello", p2 : "World"}), 5000);