最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS. Autorefresh $scope variable in html - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Jan 24, 2013 at 11:45 Paul KononenkoPaul Kononenko 9,4274 gold badges20 silver badges13 bronze badges 2
  • what is $scope object? is it a variable for textbox? – Syed Salman Raza Zaidi Commented Jan 24, 2013 at 11:46
  • @SyedSalmanRazaZaidi That's an AngularJS thing. – 11684 Commented Jan 24, 2013 at 12:06
Add a comment  | 

3 Answers 3

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

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

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

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

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>
发布评论

评论列表(0)

  1. 暂无评论