【问题标题】:Difference between $interval and setInterval in AngularJsAngularJs 中 $interval 和 setInterval 的区别
【发布时间】:2015-08-08 03:50:16
【问题描述】:

我试图了解 $interval 和 setInterval 之间的区别。 我有这个测试:

Dashboard.prototype.updateTotalAppointments = function(){
//console.log();
this.appointmentsCount = this.appointmentsCount +1;
console.log(this.appointmentsCount);
};

Dashboard.prototype.start = function(){
    setInterval(function(){
        this.updateTotalAppointments();
    }.bind(this), 3000);
}

>

div class="hb-info-card-data-count"><h1>{{dashCtrl.appointmentsCount}}</h1></div>

使用 setInterval 不会更新 HTML 页面上的值,但该值实际上会在浏览器控制台上发生变化,只是不会在 Html 页面上更新。

但如果我这样做:

Dashboard.prototype.start = function(){
$interval(function(){//using $interval seems to work fine
    this.updateTotalAppointments();
}.bind(this), 3000);

}

这似乎工作得很好,所以我真的不知道为什么后者没有工作, 但我真的很想知道。

还有什么是不断从后台请求数据的最佳方式,比如每 n 分钟一次并通过其控制器更新页面。

【问题讨论】:

    标签: javascript jquery angularjs


    【解决方案1】:

    $interval 是 Angular 对原生 Javascript setInterval 的封装。

    当使用$interval 时,Angular 会知道区间函数所做的任何作用域更改,并且双向绑定会反映这些更改。

    当使用setInterval 时,Angular 将不知道 setInterval 函数所做的任何范围更改。

    简单地说,$interval 函数会触发 Angular 的摘要循环,而 setInterval 不会。

    This plunkr 展示了不同之处。

    代码:

    angular.module('DemoApp', [])
      .controller('IntervalCtrl', function($scope, $interval) {
    
    
        var updateExampleText = function() {
          console.log('Changing exampleText');
          $scope.exampleText = 'Time: ' + new Date().getSeconds();
        };
    
        $scope.useInterval = function() {
          //Show current seconds value 5 times after every 1000 ms
          $interval(updateExampleText, 1000, 5);
    
        };
    
        $scope.useSetInterval = function() {
          //$scope.exampleText changes are not reflected in the page
          //because Angular is not aware of the changes.
          setInterval(updateExampleText, 1000);
        };
      });
    

    【讨论】:

    • “当使用 $interval 时,Angular 会知道间隔函数所做的任何范围更改”。 正是。 +1
    • 谢谢,这澄清了我的疑问,至少我知道我现在在做什么,但是角度文档是:( ....
    【解决方案2】:

    $interval 是 setInterval AND $apply 同时的包装。它使作用域变量的更新在 $interval 上发生时可见。也适用于 $timeout

    【讨论】:

      猜你喜欢
      • 2019-01-11
      • 1970-01-01
      • 2021-09-24
      • 2011-02-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多