AngularJS。在html中自动刷新$ scope变量

时间:2013-01-24 11:45:04

标签: javascript html templates angularjs

如何在$ scope对象中触发自动变量?

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

//template
{{rand}}

Rand在我的页面上没有更新。如何更新我的变量?

3 个答案:

答案 0 :(得分:10)

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

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

演示:http://jsbin.com/udagop/1/

答案 1 :(得分:6)

实际上,最直接的方式是:

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

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

  $interval(update, 1000);
}

这就是setInterval()

的Angular等价物

答案 2 :(得分:3)

你可以这样做:

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

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