2013-01-24 32 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()的角等價物