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}}
$ 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