Pete Alvin
Pete Alvin

Reputation: 4790

Angular ng-bind only binds once

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.

Upvotes: 0

Views: 227

Answers (2)

Farzad Yousefzadeh
Farzad Yousefzadeh

Reputation: 2551

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

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

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);
  }]);

Upvotes: 5

Related Questions