2013-01-24 9 views
6

Wie kann ich automatisch meine Variable bei $ Scope-Objekt triggern?

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

//template 
{{rand}} 

Rand ist kein Update auf meiner Seite. Wie kann ich meine Variable aktualisieren?

+0

Was ist $ Scope-Objekt? ist es eine Variable für Textbox? –

+0

@SyedSalmanRazaZaidi Das ist eine AngularJS-Sache. – 11684

Antwort

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

Sie tun können:

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

und

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

eigentlich die Angularish Weg, dies zu tun wäre:

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

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

    $interval(update, 1000); 
} 

Das ist das Winkeläquivalent von setInterval()