Tips for eliminating flickering when updating arrays in angular

Attempting to maintain real-time updates on an Angular page by polling a REST service hosted locally and updating the array with new content is crucial. The code snippet below demonstrates this:

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>

The snippet used above might cause flickering issues:

 reg.teacherInfoList[0] = response.data;

Flickering may also occur with the following code:

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

Efforts have been made to resolve the issue using:

ng-cloack

Also tried:

track by $index

Additionally, referring to this article:

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

Although a solution eludes me currently, it's evident that replacing the array momentarily results in flickering. Any suggestions on how to overcome this challenge effectively?

Answer â„–1

reg.teacherInfoList.length = 0;

Maybe it's not necessary to empty the array in this case. It seems like the teacherInfoList array remains empty throughout the request, resulting in a blank render. You might want to consider either removing or commenting out the line above, or moving it to the beginning of the callback function for the GET request as shown below:

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Enjoy seamless page transitions with SPA implemented using AngularJS, where navigation occurs without any

I recently developed a small SPA application using Angularjs and Bootstrap. I followed all the specifications provided by Angular's website and other resources online. In order to dynamically include other pages in the main page, I utilized ng-view. ...

Unable to retrieve data when utilizing SWR and Context API in Next.js

I'm currently working on fetching data from an API using SWR and dynamically setting the currency based on user preferences through context API. However, I'm facing issues as I am unable to view any data. Can someone please provide assistance or ...

Once the Ionic platform is prepared, retrieve from the Angular factory

I have created a firebase Auth factory that looks like this: app.factory("Auth", ["$firebaseAuth", "FIREBASE_URL","$ionicPlatform", function($firebaseAuth, FIREBASE_URL, $ionicPlatform) { var auth = {}; $ionicPlatform.ready(function(){ ...

How can I retrieve the latest state of the Redux store in getServerSideProps in Next.js?

I am attempting to retrieve the most up-to-date redux state in getServerSideProps like so: export const getServerSideProps = async (ctx) => { const state = store.getState(); console.log(state.name); return { props: { login: false } }; }; H ...

Unexpected glitch when assigning arrays in Angular 2+?

I have a simple question that has been puzzling me. When attempting to reassign an element of an array of objects to another object that meets specific criteria, I noticed that nothing happens. However, if I first set the element to null and then reassign ...

JavaScript function is not identifiable

I am currently developing a tic-tac-toe game with 9 buttons that will display either an X or O image depending on the boolean value of the variable isX. The main container for these buttons is a div element with the id 'stage' and each button ha ...

What occurs when a numerical value is added to an element within an array?

Illustration 1: Let numbers = [4,5,6] + 2; console.log(numbers) // "4,5,62" typeof numbers // String Illustration 2: let nums = 10 + ["w","o","r","l","d"]; console.log(nums) // "10w,o,r,l,d"; typeof nums // String When combining a number or string wi ...

Testing the methods declared within another method in Node.js using unit tests

I have a node module with the following structure: 'use strict’; /// require dependencies here function outerFunc1(a, b, c) { function f1() { return f2() } function f2() { return 2 } f1(); } const choose = (type) => { le ...

Utilize Uppercase Letters in React Routes

I am currently developing a simple React application, but I have encountered an unusual issue with the router. It always capitalizes the first letter of the pathname and I cannot figure out why. app.js import React from "react"; import ReactDOM from "rea ...

How to retrieve the value of a selected radio button in an AngularJS radio button group that uses ng-repeat

In the following code snippet, I am trying to retrieve the value when any of the radio buttons is selected: <label ng-repeat="SurveyType in SurveyTypes"> <input type="radio" name="SurveyTypeName" ng-model="surveyData.SurveyTypeN ...

Executing the Correct Command to Import a CSV File into MongoDB using OSX Terminal

I am attempting to upload a TSV file into Mongodb, but my lack of familiarity with Terminal is causing issues. I keep receiving an error when trying to execute the following command. Can anyone provide guidance? /mongoimport --db webapp-dev --collection ...

JavaScript: Modifying the Style of a :lang Selector

Currently, I am working on creating a basic multilingual static website using only HTML5, CSS3, and vanilla JavaScript. The structure of the HTML looks something like this: <html> <head> <title>WEBSITE</title> ...

Trouble with refreshing view - angular, firebase

I've been struggling with getting this function to fire more than once, even though it should update when scope.job.getApplicants() changes. I've tried various methods like $watch, $apply, and firebase's ref.on('value', but nothing ...

Having trouble triggering the button with querySelector in Angular

I have a dynamic page where I need to click on a button. I tried the code below, but it is not working and not showing any alert. However, if we use the same code in the browser console, it executes and shows an alert. Can someone please suggest how to r ...

The interfaces being used in the Redux store reducers are not properly implemented

My Redux store has been set up with 2 distinct "Slice" components. The first one is the appSlice: appSlice.ts import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import type { RootState } from "./store"; export interface CounterState { value ...

There is no Api.js file in the Cordova iOS platform

I have been attempting to integrate the iOS platform into a new Cordova 7.0.1 project, but I continuously encounter the error mentioned in the title of this post. Despite following the steps outlined in this thread here, including removing and re-adding ...

What is the reason behind $('#id').val() not functioning properly when document.getElementById('id').value is working flawlessly?

$('#id').val() = $.cookie("name"); - does not function as expected, no changes occur document.getElementById('id').value = $.cookie("name"); - works properly What is the reason behind this inconsistency? ...

Formik's setField function is not properly updating the value of an array when using Material UI's autocomplete

When the data is retrieved from the API, it comes in the following format: otherLanguages:[{code:EN,name:"English"},{code:MD,name:"Mandarin"}] I am attempting to initialize the Autocomplete with this data: initialValues: { otherLa ...

Adjusting the timing of a scheduled meeting

Is there a way for me to update the time of a Subject within my service? I'm considering abstracting this function into a service: date: Date; setTime(hours: number, mins: number, secs: number): void { this.date.setHours(hours); this.date.s ...

Enroll a click event handler in AngularJS using the ng-click directive

I am trying to designate a class for an element using ng-click. However, even though ng-click successfully sets the value, ng-class is not recognizing it on the same element: <button class="button" ng-click="selected=2;" ng-class="{active:selected== ...