【问题标题】:AngularJS. Autorefresh $scope variable in htmlAngularJS。 html中的自动刷新$范围变量
【发布时间】:2013-01-24 11:45:03
【问题描述】:

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

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

//template
{{rand}}

我的页面上没有更新兰德。如何更新我的变量?

【问题讨论】:

  • 什么是 $scope 对象?它是文本框的变量吗?
  • @SyedSalmanRazaZaidi 这是 AngularJS 的事情。

标签: javascript html templates angularjs


【解决方案1】:
function MyCtrl($scope, $timeout) {
  $scope.rand = 0;

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

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

【讨论】:

    【解决方案2】:

    实际上,最 Angularish 的做法是:

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

    这就是 setInterval() 的 Angular 等价物

    【讨论】:

      【解决方案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>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-09-07
        • 1970-01-01
        • 2013-05-31
        • 1970-01-01
        • 1970-01-01
        • 2011-10-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多