问题
I would like to create a static javascript variable to be used as a counter inside a Angularjs controller. This static variable will be used inside a polling function that gets repeatedly called.
I want to use the static variable in a manner that looks like this;
var polling_func = function()
{
static var counter = 0;
if (counter == 10)
{
alert('Do action');
counter = 0;
}
counter = counter + 1;
$timeout(polling_func, 1000);
}
polling_func();
Unfortunately, I cannot declare a static variable using static keyword in javascript. How should I go about doing so in my code?
回答1:
Why not declare a global variable, so it will not change the value whenever function is called.
var counter = 0;
var polling_func = function()
{
if (counter == 10)
{
alert('Do action');
counter = 0;
}
counter = counter + 1;
}
polling_func();
$timeout(polling_func, 1000);
回答2:
I think @Naeem-Shaikh's answer is the simplest one, and pure JS.
But since you flagged angular, there is a more Angular-ish way to do it: use a service.
app.factory('Counter',function() {
return {c:0};
});
and then in your controller (or multiple controllers):
app.controller('MyCtrl',function(Counter) {
Counter.counter++;
});
factories/services are intended to be long-lived and pass methods and variables around between short-lived controllers.
If all you need is a var (i.e. no methods) like here, there is a short-hand:
app.value('Counter',{counter:0});
And then use it in controllers in the same way.
来源:https://stackoverflow.com/questions/27145109/static-javascript-variable-to-be-used-as-counter-in-angularjs-controller