AngularJs中$ interval和setInterval之间的差异 [英] Difference between $interval and setInterval in AngularJs

查看:347
本文介绍了AngularJs中$ interval和setInterval之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to understand what's the difference between $interval and setInterval. I have this test:

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页面上没有更新。

Using setInterval doesn't update the value on the HTML page, but the value actually changes on the browser console, but it just doesn't get updated on the Html page.

但如果我这样做:

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

}

这似乎完美无缺,所以我真的不知道为什么后者不起作用,
但我真的很想知道。

This seems to work perfectly, so i really don't know why the latter didn't work, but i would really like to know please.

还有什么是从背景中不断请求数据的最佳方式是每隔n分钟,并通过其控制器更新页面。

And also what will be the best way to constantly request data from the background lets say every n-minutes and update the page via its controller.

推荐答案

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

$interval is Angular's wrapper for the native Javascript setInterval.

当使用 $ interval 时,Angular会知道间隔函数所做的任何范围更改,以及两者-way binding反映了这些变化。

When $interval is used, Angular is aware of any scope changes made by the interval function, and the two-way binding reflects the changes.

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

When setInterval is used, Angular will not be aware of any scope changes made by the setInterval function.

简单地说, $ interval 函数触发Angular的摘要周期,而 setInterval 没有。

Put simply, the $interval function triggers Angular's digest cycle while setInterval does not.

此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);
    };
  });

这篇关于AngularJs中$ interval和setInterval之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆