gpt4 book ai didi

javascript - 如何防止 Angular 数组更新闪烁

转载 作者:行者123 更新时间:2023-11-30 00:08:04 26 4
gpt4 key购买 nike

在 Angular 上,我试图通过轮询 REST 服务(本地托管)来保持我的页面实时,并使用新检索的内容更新我的数组,如下所示:

JS

angular.module("WIMT").controller('overviewController', function ($scope,$interval,$http){
var reg = this;
var promise;

reg.teacherInfoList = [];

reg.dayfilter = "";


$scope.start = function() {
$scope.stop();

promise = $interval( $scope.longPolling, 3000);
};

$scope.stop = function() {
$interval.cancel(promise);
};

$scope.longPolling = function(){

reg.teacherInfoList.length = 0;

$http({
method: 'GET',
url: 'api/schedules/' + "TPO01"
}).then(function onSuccessCallback(response) {

reg.teacherInfoList[0] = response.data;
console.log(reg.teacherInfoList[0]);

$scope.start();
}, function errorCallback(response) {
$scope.start();
});
}


$scope.start();

});

HTML

<div ng-controller="overviewController as oc">

<ul>
<li ng-repeat="teachInfo in oc.teacherInfoList ">
{{teachInfo.fullname}}

<div ng-repeat="day in teachInfo.days | filter: oc.dayfilter">
Today is: {{day.day}} {{day.date}}

<ul ng-repeat="roster in day.entries">
<li>
Name: {{roster.name}}
</li>
<li>
Start: {{roster.start}}
</li>
<li>
End: {{roster.end}}
</li>
<li>
Note: {{roster.note}}
</li>
</ul>

</div>

</li>
</ul>

如上使用的代码导致闪烁:

 reg.teacherInfoList[0] = response.data;

这段代码也会导致闪烁:

 reg.teacherInfoList.splice(0,1);
reg.teacherInfoList.splice(0,0,response.data);

我也尝试将其应用于我的 ng-repeats:

ng-cloack

并将其应用于我的 ng-repeats

track by $index

我也看过这个:

How does the $resource `get` function work synchronously in AngularJS?

现在,我知道当我更换我的数组时,数组会短暂地变空,导致它闪烁,但我想不出解决这个问题的方法。解决此问题的最佳方法是什么?

最佳答案

reg.teacherInfoList.length = 0;

不确定这里是否需要清空数组。我相信 teacherInfoList 数组在整个请求期间都是空的,导致它呈现为空白。您可以尝试删除(或注释掉)上面的行或将其移动到 GET 请求的回调函数的顶部,例如

    }).then(function onSuccessCallback(response) {
// applied here
reg.teacherInfoList.length = 0;
reg.teacherInfoList[0] = response.data;
console.log(reg.teacherInfoList[0]);

$scope.start();
}, function errorCallback(response) {
//and here
reg.teacherInfoList.length = 0;
$scope.start();
});

关于javascript - 如何防止 Angular 数组更新闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37704272/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com