0

The browser console shows $scope.counter incrementing but why doesn't the page increment?

It shows "counter=100" so I know the bind worked once, but not (101, 102, ...) subsequent times as the timer fires:

<!DOCTYPE html>
<html ng-app="bindInterval">
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
  <script>
    angular.module('bindInterval', [])
      .controller('bindIntervalController', ['$scope', function($scope) {
        $scope.counter = 100;
        window.setInterval(function() {
          $scope.counter += 1;
          console.log($scope.counter);
        }, 1000);
      }]);
  </script>
</head>
<body><div ng-controller="bindIntervalController">counter={{counter}}</div></body>
</html>

Code at Plunker

I've Googled this but they only show {{::name}} which is different.

1
  • Also stuck at 100: <span ng-bind="counter"></span> Commented Oct 14, 2015 at 18:17

2 Answers 2

5

Because setInterval doesnt trigger a digest cycle. You need to use the $interval module provided by Angular:

angular.module('bindInterval', [])
  .controller('bindIntervalController', ['$scope', '$interval' function($scope, $interval) {
    $scope.counter = 100;
    $interval(function() {
      $scope.counter += 1;
      console.log($scope.counter);
    }, 1000);
  }]);
Sign up to request clarification or add additional context in comments.

Comments

1

Do not use setInterval in angularjs because angular would not see the changes that way. use $interval instead.

Comments

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.