如何防止角度更新阵列更新闪烁

时间:2016-06-08 13:43:27

标签: javascript angularjs

在角度方面,我试图通过轮询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?

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

1 个答案:

答案 0 :(得分: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();
    });