Need help with writing code in Angular for setting intervals and clearing intervals?

I am working on the functionality to display a loader gif and data accordingly in Angular. I have tried using plain JavaScript setInterval code but it doesn't work for $scope.showLoader=true and $scope.showResult=true. The console.log('found the ...') statement works, but the first 2 statements (show hide) do not work. The loader keeps rotating and the data does not display. Do you think using angular $setTimeout would work instead?

        
$scope.showLoader = true;
$scope.showResult = false;

var timer = setInterval(function(){

    if($scope.resultArray.length == 4) {
        clearInterval(timer);
        $scope.showResult = true;     // doesn't work               
        $scope.showLoader = false;    // doesn't work
        console.log('found all search results'); // it works

    }

},200);

Answer №1

This seems like a common issue encountered while working with Angular. The problem arises when Angular is not aware of the updates made to variables showLoader and showResult within the timer function. To resolve this, you need to explicitly notify Angular by calling $scope.$apply() after updating these variables. By doing so, Angular will be able to detect the changes and reflect them in the UI successfully. I hope this solution proves helpful for you.

    $scope.showLoader = true;
    $scope.showResult = false;

    var timer = setInterval(function(){

        if($scope.resultArray.length == 4) {
            clearInterval(timer);
            $scope.showResult = true;     // update now recognized               
            $scope.showLoader = false;    // update now recognized
            $scope.$apply();
            console.log('found all search results'); // indication of successful change detection

        }

    },200);

Answer №2

To rectify this issue, consider incorporating the $scope.$apply method. The current problem lies in Angular's inability to detect changes made by asynchronous JavaScript functions, unless specific Angular methods such as $timeout are used. By using $apply, you can prompt Angular to check for modifications by initiating a digest cycle. However, an alternative approach could be utilizing $watch.

$scope.$watch('resultArray', function(resultArray) {
   if(resultArray.length == 4) {
       $scope.showResult = true;           
       $scope.showLoader = false;
       console.log('all search results found');
   }
});

As suggested by Kevin, the optimal solution may involve passing your method into the section of code that updates the resultArray. This will allow it to execute as a callback upon completion.

Answer №3

The crux of the issue lies in your attempt to update properties on the $scope within a setInterval function. Utilizing Angular's $interval or incorporating $scope.apply into the interval callback can resolve this issue. These methods trigger a digest cycle, leading to the view updating with the new scope values.

Alternatively, a more efficient approach would be to update these properties at the same location where you populate the array. This approach minimizes the number of digest cycles (at least one less) and allows the view to update promptly without waiting for an interval to complete.

$scope.showLoader = true;
$scope.showResult = false;
someService.getData().then(function (data) {
    $scope.resultArray = data.data;
    $scope.showResult = true;
    $scope.showLoader = false;
});

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

What possible reasons could be causing the code to not run after my for loop?

<script> //grab all the input values when submit button is clicked const sub = document.getElementById("sub"); sub.addEventListener("click", (e) => { e.preventDefault(); //get input values var ...

Disabling ngIf but still utilizing ngContent will render the template bindings

Creating a basic component in the following way: @Component({ selector: 'loader', template: `<div *ngIf='false'> <ng-content></ng-content> </div>`, }) export class Loader {} When it is imple ...

Running a JavaScript asynchronous function and capturing the output using Selenium

Attempting to run the script below in Selenium result = driver.execute_script('let result; await axe.run().then((r)=> {result=r}); return result;') Results in an error: Javascript error: await is only valid in async function Another at ...

Keep only certain fields and eliminate the rest

Write a function that filters out all fields except 'firstName' and 'lastName' from the objects. Check out this code snippet I came up with. Any feedback? let people = [ { firstName: 'John', lastName: &apo ...

Tips for replacing default arrow icons with 'Previous' and 'Next' buttons in a Material-UI pagination element

I've been struggling to find a solution with my code provided below. Despite multiple attempts, the issue remains unresolved. import React from "react"; import { gridPageCountSelector, gridPageSelector, gridPageSizeSelector, useGridA ...

Tips on removing either the date or time when input type date and input type time share the same ng-model

In my Ionic app built with AngularJS, I have a form where the date and time are displayed separately but share the same data-ng-model: <input type="date" id ="actualVisitDate" data-ng-model="actualVisitDate" required> <input type="time" id ="actu ...

"I'm encountering an issue with Passport.js where req.isAuthenticated is throwing an error as not

Recently I started working with node and express, along with passport.js for building an authentication feature. However, I encountered an issue while using a middleware function called "checkNotAuthenticated" in my routes. The error message I received was ...

Looking to display database information using javascript

Currently, I am working on a project involving PHP code where I retrieve variables from an input and utilize AJAX. Here is the code snippet: $.ajax({ type: "GET", url: "controller/appointment/src_agenda.php", data: { function: "professional", ...

Utilize the v-for second argument in VueJS 2 to showcase the index and index+1

For a VueJS 2 project, I am tasked with enhancing the display of the first and second elements in an array by making them stand out from the rest. To achieve this, I am utilizing the v-for syntax to iterate over a child component within a parent component. ...

Display the chosen alternative in a Bootstrap dropdown menu

I am currently facing an issue with the dropdown list in my bootstrap menu. <li class="dropdown"> <a aria-expanded="false" aria-haspopup="true" role="button" data-toggle="dropdown" class="dropdown-toggle" href="#">Chose option<span class="c ...

Discover the object in the initial array that is not included in the second array using AngularJS

Imagine having these two sets of objects: first set: [ { id: "123", title: "123", options: [] }, { id: "456", title: "456", options: [ { id: "0123", t ...

Executing numerous xhttp.send requests within a single webpage

Hey there, I'm facing an issue with xhttp.send(); as it keeps giving me the error message net::ERR_EMPTY_RESPONSE Here is a snippet of my code. Whenever a user clicks too quickly, they get kicked off the page. Is there a way to prevent this? docum ...

Angular model remains static when incorporated within the document.addEventListener() attribute

Can anyone help me figure out why my attempt to update the model name this.name on click inside document.getElementById('source-selection').addEventListener is not working? Surprisingly, a simple alert within that function does trigger successful ...

Navigating through hidden input fields in Angular by utilizing the tab key

Seeking a method in Angular to navigate hidden inputs using tab functionality. I have several input forms that display only the text when not on focus. Is there a way to select an input and still be able to tab through the other hidden inputs? Any ideas o ...

Determine which JavaScript script to include based on whether the code is being executed within a Chrome extension

I am in the process of developing a Chrome extension as well as a web JavaScript application. I currently have an HTML container. I need the container.html file to include <script src="extension.js"> when it is running in the Chrome extension, and ...

The ZIP file downloaded from NodeJS is corrupted and cannot be opened

Currently, I am utilizing the following code to create a MySQL dump in memory, then zip that SQL file with a password from memory and save it to the hard drive so it can be streamed to the client... /* DUMP - database */ var mysqld ...

Completing the final touches on my jQuery typing enhancement feature

Currently, I have a code snippet that creates <li> elements with specific dimensions and background images when a user presses a key. The corresponding CSS class is applied to the generated <li>, displaying a specific character on the screen. H ...

How to add and append values to an array in a Realtime Database

My React.js app allows users to upload songs to Firebase and view the queue of uploaded songs in order. The queue can be sorted using a drag-and-drop system that updates the database in Firebase. Is there a way to insert these songs into an array when uplo ...

Using React Refs to Trigger the video.play() Method - A Step-by-Step Guide

Is there a way to use a ref in order to trigger video.play()? Currently encountering an error: preview.bundle.js:261916 Uncaught TypeError: _this2.videoRef.play is not a function Take a look at my component: import React from 'react'; import s ...

Mastering the use of getText() in Protractor with Page Object Model in Javascript

Having trouble retrieving specific values from my page object. The getText() method is returning the entire object instead of just the text, likely due to it being a Promise. I can provide my code if necessary, but I'm aiming to achieve something sim ...