6

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?

2
  • what is $scope object? is it a variable for textbox? Commented Jan 24, 2013 at 11:46
  • @SyedSalmanRazaZaidi That's an AngularJS thing. Commented Jan 24, 2013 at 12:06

3 Answers 3

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

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

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

Sign up to request clarification or add additional context in comments.

Comments

6

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()

Comments

3

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>

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.