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.

4

1 回答 1

1

您需要$scope.$apply()在回调内部使用,setInterval以便值更新。

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

通常建议使用$timeout而不是(因为它可以防止需要),这是一个很好的方法:https ://stackoverflow.com/a/14238039/1266600 。setInterval$apply

于 2013-09-05T22:58:33.953 回答