3

I have an input field that I would like to show a simple counter (updated per second).

<input class="form-control input-lg" type="text" placeholder="00" ng-model="ss">

The start/stop buttons each have associated ng-click methods in the controller

View

<button ng-click="start()">Start</button>

Can I accomplish a counter within the controller functions?

$scope.start = function() {

};

I tried something like this

$scope.start = function() {
    if($scope.counting === true) return false;
    $scope.counting = true;
    $scope.counter = setInterval($scope.updateCount, 1000);
};

$scope.updateCount = function() {
    $scope.ss++;
}

But when the start function is called, the value is not updating the input ng-model='ss' continually. It just sets it to 1 and then the interval doesn't seem to continue updating.

Or do I need to create a service? If so, can someone point me in the right direction for how that service would need to be setup in order to return an updating count value back to the controller.

Any help is appreciated as usual.

tereško
  • 58,060
  • 25
  • 98
  • 150
Jbird
  • 2,839
  • 1
  • 21
  • 28

1 Answers1

1

You need to use $scope.$apply() inside the setInterval callback so that the value updates.

$scope.updateCount = function() {
    $scope.ss++;
    $scope.$apply();
}

Using $timeout rather than setInterval is generally recommended (since it prevents the need for $apply), here is a good way to do it: https://stackoverflow.com/a/14238039/1266600.

Community
  • 1
  • 1
sushain97
  • 2,752
  • 1
  • 25
  • 36
  • Thank you very much - $apply is exactly what I needed. The function did originally use $timeout but I tried setInterval thinking that the issue may have been related to $timeout. Thank you for clarifying and for the link. In your opinion, do you think this warrants a service? – Jbird Sep 05 '13 at 23:11
  • Unless you will be using it as a reusable component in multiple controllers, creating a service is probably overkill :) – sushain97 Sep 05 '13 at 23:19
  • 2
    Unless there is a good reason to not use `$timeout`, it is probably best for you to just use `$timeout` instead. – Brian Genisio Sep 05 '13 at 23:50
  • @BrianGenisio I agree and the answer has already pointed this out. My comment explains that I was simply trying setInterval in case the update issue was related to the $timeout service. – Jbird Sep 05 '13 at 23:54