AngularJs中$ interval和setInterval之间的差异

我试图理解$ 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">

{{dashCtrl.appointmentsCount}}

使用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则不会。

这个plunkrcertificate了差异。

码:

 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