Paul Kononenko
Paul Kononenko

Reputation: 9427

AngularJS. Autorefresh $scope variable in html

How can I trig automatic my variable at $scope object?

//controller
setInterval(function(){$scope.rand=Math.random(10)},1000);

//template
{{rand}}

Rand is not update on my page. How can I update my variable?

Upvotes: 6

Views: 9021

Answers (3)

alcfeoh
alcfeoh

Reputation: 2267

Actually the most Angularish way to do that would be:

function MyCtrl($scope, $interval) {
  $scope.rand = 0;

  function update() {
    $scope.rand = Math.random() * 10;
  }

  $interval(update, 1000);
}

That's the Angular equivalent of setInterval()

Upvotes: 6

Yoshi
Yoshi

Reputation: 54659

function MyCtrl($scope, $timeout) {
  $scope.rand = 0;

  (function update() {
    $timeout(update, 1000);
    $scope.rand = Math.random() * 10;
  }());
}

demo: http://jsbin.com/udagop/1/

Upvotes: 10

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100205

you could do:

//controller    
function UpdateCtrl($scope) {
    $scope.rand = 0;
    setInterval(function() {
       $scope.$apply(function() {
          $scope.rand = Math.random(10);
       });
    }, 1000);            
}

and

//template
<div ng-controller="UpdateCtrl">
{{rand}}    
</div>

Upvotes: 3

Related Questions