2013-01-24 11 views
6

$ scopeオブジェクトの自動変数をトリガーする方法はありますか?

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

//template 
{{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()の等価円相当です