Skip to content Skip to sidebar Skip to footer

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 rep

Solution 1:

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.

Solution 2:

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);

Post a Comment for "Static Javascript Variable To Be Used As Counter In Angularjs Controller"