【问题标题】:How to prevent flickering on array updates in angular如何防止在角度数组更新时闪烁
【发布时间】:2016-06-08 22:00:10
【问题描述】:

在 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?

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

【问题讨论】:

  • 您可以尝试修改值而不删除,只有在新响应没有具有相同id的记录时才删除行。
  • 闪烁是否每 3 秒发生一次?是页面上的信息在闪烁吗?通过克隆 DOM 元素的最后一个状态并无缝 对其进行缓冲以在闪烁发生时显示,也许会造成闪烁不会发生的错觉。

标签: javascript angularjs


【解决方案1】:
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();
    });

【讨论】:

  • 感谢它有效,我删除了 reg.teacherInfoList.lenght = 0;我添加该部分的原因是由于 ng-repeat 无法处理的重复项。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-11
  • 2010-09-10
  • 2020-05-07
  • 1970-01-01
相关资源
最近更新 更多