2013-01-24 31 views
6

Làm thế nào tôi có thể trig tự động biến của tôi tại đối tượng $ scope?

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

//template 
{{rand}} 

Rand không cập nhật trên trang của tôi. Làm cách nào để cập nhật biến của tôi?

+0

đối tượng $ scope là gì? nó là một biến cho textbox? –

+0

@SyedSalmanRazaZaidi Đó là một điều AngularJS. – 11684

Trả lời

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

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

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

3

bạn có thể làm:

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

Trên thực tế cách Angularish nhất để làm điều đó sẽ là:

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

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

    $interval(update, 1000); 
} 

Đó là tương đương Góc của setInterval()