Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static javascript variable to be used as counter in Angularjs controller

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?

like image 550
guagay_wk Avatar asked Dec 05 '25 12:12

guagay_wk


1 Answers

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.

like image 91
deitch Avatar answered Dec 07 '25 02:12

deitch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!