2013-01-24 30 views
6

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

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

//template 
{{rand}} 

Rand在我的页面上没有更新。我怎样才能更新我的变量?

+0

什么是$ scope对象?它是一个文本框的变量? –

+0

@SyedSalmanRazaZaidi这是一个AngularJS的东西。 – 11684

回答

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

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

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

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> 
6

其实最Angularish办法做到这一点是:

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

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

    $interval(update, 1000); 
} 

这就是setInterval()的角等价物