AngularJs中$interval和setInterval的区别

Difference between $interval and setInterval in AngularJs

本文关键字:setInterval 区别 interval AngularJs      更新时间:2023-09-26

我试图了解$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分钟通过它的控制器更新页面

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

当使用$interval时,Angular会意识到interval函数所做的任何作用域变化,并且双向绑定会反映这些变化。

当使用setInterval时,Angular将不会意识到setInterval函数所做的任何作用域更改。

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

这个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是setInterval和$apply的换行符。当$interval发生时,它使作用域变量的更新可见。同样适用于$timeout