如何防止 angular 中数组更新的闪烁

How to prevent flickering on array updates in angular

提问人:Niek Jonkman 提问时间:6/8/2016 最后编辑:CommunityNiek Jonkman 更新时间:6/8/2016 访问量:4849

问:

在 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

我也读过这个:

$resource“get”函数如何在 AngularJS 中同步工作?

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

Javascript AngularJS 的

评论

0赞 E. Abrakov 6/8/2016
您可以尝试在不删除的情况下修改值,并且仅当新响应没有具有相同 ID 的记录时才删除行。
0赞 Alexander Dixon 6/8/2016
闪烁是否每 3 秒发生一次?是页面上的信息闪烁了吗?也许通过克隆 DOM 元素的最后状态并在闪烁发生时无缝地对其进行抛光以显示,从而产生一种不会发生闪烁的错觉。

答:

1赞 Kiz 6/8/2016 #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();
    });

评论

0赞 Niek Jonkman 6/9/2016
谢谢它有效,我删除了 reg.teacherInfoList.lenght = 0;我添加该部分的原因是 ng-repeat 无法处理的重复项。