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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With