When invoking the Angular function to make an HTTP request, it will generate a recurring loop

When trying to call a function in mg-repeat that makes an HTTP request with an ID to find a list of data, I encountered an error message.

Here is the function call:

<div ng-repeat="ListeReponse in reponsefonction(Listechamps.keyQuestion)" >
    <label class="col-xs-4 control-label">
        {{ListeReponse.reponse}}
    </label>
</div>

This is the function itself:

$scope.reponsefonction  = function(idQuestion)
{
    var defer = $q.defer();
    return RequestService.get('question/'+idQuestion+'/reponse').success(function(data) 
    { 
        defer.resolve(data);
    })
    return defer.promise;
}

Here is the service:

app.factory('RequestService', function ($http, WEB_SERVICE_URL) 
{
    var requestService = {};
    requestService.get = function (type) 
    {
        var response = $http.get(WEB_SERVICE_URL.url+type);
        return response;
    };

    // Additional methods
    requestService.post = function (type, data) 
    {
        var response = $http.post(WEB_SERVICE_URL.url+type, data);
        return response;
    };

    requestService.put = function (type, data) 
    {
        var response = $http.put(WEB_SERVICE_URL.url+type, data);
        return response;
    };

    return requestService;
})

Error message:

docs.angularjs.org/error/$rootScope/infdig?p0=10&p1=%5B%5D

Answer №1

You have unintentionally created a never-ending loop. Each function call triggers another, resulting in continuous calls. Angular continually assesses the responseFunction during these calls. It is advisable to make some adjustments to your application:

Avoid calling a function within ng-repeat. Instead, connect it directly to a variable. Populate the variable once during app initialization with a get query.

Answer №2

It seems that using ng-repeat with promises may not be supported. When ng-repeat tries to loop through "null/undefined" values, it can trigger an error.

Here's a possible solution:

HTML:

<div ng-repeat="ResponseList in fetchResponses(QuestionList.key)" >
    <label class="col-xs-4 control-label">{{ResponseList.response}}</label></div>

Controller:

var questionIDs = {}; // to keep track of the full list
$scope.fetchResponses = function(questionID) {
  var uninitialized = questionIDs[questionID] == null;
  questionIDs[questionID] = uninitialized ? [] : questionIDs[questionID]; // initialize as an empty array
  if (uninitialized) {
    $scope.responseFunction(questionID); // starts an AJAX request to retrieve data
  }
  return questionIDs[questionID];
}

$scope.responseFunction = function(questionID) {
  RequestService.get('question/' + questionID + '/response').success(function(data) {
      // assuming data is an array
      Array.prototype.push.apply(questionIDs[questionID], data); // updates the same array object to avoid multiple $digest cycles

    }
  }
}

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

I encountered issues with my Bower calls being blocked by the corporate proxy, which resulted in errors when attempting to update my

When attempting to install bower through npm for the angular seed project setup, I encountered errors due to my corporate proxy causing issues. retry Request to https://bower.herokuapp.com/packages/angular failed with ECONNRESET, retrying in 1.2s bower ...

Using the `on` method of jQuery to make an Ajax request

I'm facing a challenge with using Jquery to load dynamic wall posts for followers. The issue arises when trying to work with dynamic content in the traditional click method. To solve this, I have implemented the on method for the response. However, I ...

Issues with importing Three.js as a module - encountering an Uncaught SyntaxError:

I am currently delving into the world of three.js and working on my first project. I am following the example code provided on the three.js website. Everything runs smoothly when I have three.js stored in a folder like: js/ directory However, I am enco ...

The module "jquery" in jspm, jQuery, TypeScript does not have a default export

Having some trouble setting up a web app with TypeScript and jspm & system.js for module loading. Progress is slow. After installing jspm and adding jQuery: jspm install jquery And the initial setup: <script src="jspm_packages/system.js"></scri ...

Limiting click event to only Image component in Next.js

Is there a way to trigger a click event only on the image itself, rather than the entire parent div? When setting width and height for the parent div, the click event seems to encompass the entire area. For instance, if the image is 600 pixels wide by 300 ...

Is there a way to dynamically replace a section of a link with the current URL using JavaScript or jQuery?

I have a link that appears on multiple pages, and I want to dynamically change part of the link based on the current URL* of the page being visited. (*current URL refers to the web address shown in the browser's address bar) How can I use JavaScript ...

Is there a way to validate form elements in HTML prior to submitting the form?

In my form, I am utilizing PHP for validation and processing, but I am interested in verifying elements as they are being filled out. Is there a way to check the current value of an element before the form is submitted? ...

Exploring the KEY attributes within a JSON dataset

In my React project, I am working on displaying specific key values from a JSON response. For example, the fieldData {DMR_5_why_who_test: "test", why: test}. My goal is to only show the bolded or key values in my output. However, my current code is not a ...

What tools do Sketchfab and Thangs utilize to display 3D models?

My website functions as a digital library for a particular niche of 3D models. However, I've noticed that the performance on mobile devices when using modelviewer to display glb files is quite poor. Frequently, the page crashes and reloads unexpectedl ...

How do you trim a string and display the final 3 characters?

When dealing with a list of objects, I want to ensure that the chain of tasks does not become too long and break the table or appear aesthetically unpleasing. Therefore, my goal is to trim the tasks and display only the last 3. In the image below, multiple ...

Retrieve documents from MongoDB database that have specific characteristics

Hello everyone, Today I'm trying to navigate mongoose queries. Imagine we have a collection like this: [ {letter: "A", name: "Books", action: "read"}, {letter: "B", name: "Notebook", action: &q ...

Uploading a JSON file to myjson.com using a jQuery PUT request in Node.js

As a novice in javascript, I have successfully retrieved a JSON object from on my HTML page using AJAX with the following code: $.getJSON("https://api.myjson.com/bins/bjm28", function (data) { $.each(data, function (index, value) { console.log ...

Maximizing the efficiency of this JavaScript code

Is there a way to optimize this code for better efficiency? I'm trying to enhance my coding skills and would appreciate some feedback on this particular section: $(function(){ $('#buscar').focus(function(){ if(($(this).val() === ...

What is the method for a HTML button to trigger the execution of a Selenium (Java) code located in a remote location through a

I need to run a Selenium Code written in Java from a NAS (Network Attached Storage) or another connected machine. My goal is to create a web page with a button that, when clicked, triggers the execution of the Selenium script located on the connected mac ...

Display different images based on user selection in vue.js

I am new to working with vue.js and I'm facing a challenge. My goal is to display images of NBA players based on the selected criteria using vue.js. For instance, if the Dunk contest champion is chosen, only images of Kobe and Jordan should be display ...

It seems that the `to` required prop was missing in the `Link` component of React-Router

Currently, I am facing an issue while trying to integrate react-router. The error message I'm encountering is: Failed propType: Required prop to was not specified in Link. Check the render method of app. Unfortunately, I am unable to pinpoint ex ...

The authorization process for uploading data to Azure Data Lake Gen2

Currently, I am working on generating a Shared Access Signature (SAS) client-side within my Node.js application. The primary goal is to allow users to directly upload files to my Azure Data Lake Gen2 Blob Storage container without streaming them through th ...

Guide on transforming a collection of files from formdata into a JavaScript object

I have a dataset containing multiple images associated with the same product id. import client from "@/lib/fetchWrapper"; export default async function addProductImage({ photo, productId, }: { photo: File[]; productId: string; }) { if ...

Is there a way for me to retrieve the pageProbs that I have shared with a Component in _app.js?

Upon the loading of my website, I am fetching a large amount of data using getInitialProps. MyApp.getInitialProps = async (appContext) => { // Calls page's `getInitialProps` and fills `appProps.pageProps` const appProps = await App.getInitialProps( ...

Transmit a cookie from the front-end to the back-end using Angular in HTTP requests

I am currently in the process of developing a web application using AngularJS. This application consists of: a frontend component that solely retrieves data from a backend through multiple queries; a backend with various RESTful services, each returning ...