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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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?
Unless you will be using it as a reusable component in multiple controllers, creating a service is probably overkill :)
Unless there is a good reason to not use $timeout, it is probably best for you to just use $timeout instead.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.