The issue of continuous requests in AngularJS controllers

In my controller, I have a simple function that calculates the number of answers for each question:

$scope.countAnswers = function(questionid) {
  AnswersQueries.getAnswers(questionid, function(answers) {
    var answersCount = answers.length;
    return answersCount;
  });
};

HTML

<!-- Inside ng-repeat -->
<div>{{countAnswers(question._id)}}</div>

Service

angular.module('app')
.factory('AnswersQueries', function ($resource) {
  return {

      getAnswers: function(questionId, callback) {

        // Define resource
        var data = $resource('api/answers?questionid=' + questionId);

        // Make the get call
        data.query().$promise.then(function(answer){

           // Return answer in callback
           callback(answer);
        });
      }
  };
});

However, when I try to reload the page, it seems to be sending multiple requests to count the questions indefinitely:

For example...

GET /api/answers?questionid=54ae02aec07933920b000001 200 28ms - 371b
GET /api/answers?questionid=54aec71cdd9a29d210000001 200 28ms - 2b
GET /api/answers?questionid=54aec75bdd9a29d210000002 200 32ms - 2b
GET /api/answers?questionid=54adf9f0e0913a590a000001 200 7ms - 2b
GET /api/answers?questionid=54ae02aec07933920b000001 200 14ms - 371b
GET /api/answers?questionid=54aec71cdd9a29d210000001 200 4ms - 2b
GET /api/answers?questionid=54aec75bdd9a29d210000002 200 4ms - 2b
GET /api/answers?questionid=54aec75bdd9a29d210000002 200 15ms - 2b
GET /api/answers?questionid=54ae02aec07933920b000001 200 18ms - 371b
GET /api/answers?questionid=54aec71cdd9a29d210000001 200 17ms - 2b
GET /api/answers?questionid=54adf9f0e0913a590a000001 200 20ms - 2b
GET /api/answers?questionid=54ae02aec07933920b000001 200 17ms - 371b
GET /api/answers?questionid=54adf9f0e0913a590a000001 200 7ms - 2b
GET /api/answers?questionid=54aec71cdd9a29d210000001 200 9ms - 2b

I noticed an error in the console (I think I can troubleshoot now... I didn't see this before because the page was frozen):

Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []

What could potentially be causing this issue?

Answer №1

Your implementation of the countAnswers function seems to be causing issues in resolving the problem.

The statement return answersCount; within the callback function is incorrect as it returns from the inner function and not from the actual countAnswers function. This leads to a situation where the function does not return any value. Since the execution of AnswersQueries.getAnswers is asynchronous, you cannot directly use its result for further operations.

To address this issue, it is recommended to store the values within the scope and update them inside the callback function.

$scope.counts = {};
$scope.countAnswers = function(questionId) {
  AnswersQueries.getAnswers(questionId, function(answers) {
    $scope.counts[questionId] = answers.length;
  });
};

// Invoke $scope.countAnswers for each question in your scope *once*

The corresponding HTML code should be structured as follows:

<div>{{counts[question._id]}}</div>

Answer №2

Angular will check every binding during a digest cycle. An automatic trigger for a digest cycle is when $resource (or rather, $http used by $resource) receives a response.

If your template binds to an expression that calls the function countAnswers, it creates a new $resource query each time. This leads to a cycle where an http call is made on digest, then another on receiving the response, and so on.

To resolve this issue, consider caching the result from the initial http call. This way, subsequent calls to 'countAnswers' will refer back to the cached result instead of making multiple http requests.

Here's an example:

var answersCounts = {};
var hasRequestedAnswers = {};
$scope.countAnswers = function(questionid) {
  if (!hasRequestedAnswers[questionid]) {
    AnswersQueries.getAnswers(questionid, function(answers) {
      answersCounts[questionid] = answers.length;
    });
    hasRequestedAnswers[questionid] = true;
  }
  return answersCounts[questionid];
};

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

Determining the specific button pressed using jQuery

There are two buttons present: <input type="button" name="hideAll" value="Hide Descriptions"/> <input type="button" name="showAll" value="Show Descriptions"/> Can someone guide me on how to determine which button has been clicked using jQuery ...

Can you show me a comprehensive list of all the REST endpoints for Express mounted Apps?

When working with Express 4, you can utilize the app._router.stack object to list your app routes. In one of the routes in my todos module routes file, I attempted to display this object by sending it as part of the response: exports.update = (req,res) = ...

Is Protractor compatible with Internet Explorer 9?

For my Angular App that is running on IE9, I need to create end-to-end acceptance tests. I'm curious to know if the browser simulated by Protractor matches the behavior of IE9 or a newer version? ...

Selenium and PhantomJS are having trouble interpreting JavaScript code

Currently experimenting with Selenium and PhantomJS for Java search tasks, I'm facing an issue where PhantomJS fails to activate javascript. My goal is to access a webpage that utilizes javascript. Previously, this method worked well for me, but now I ...

Having difficulty with pagination within a callback function

I have been attempting to paginate in a call to a callback function, but I am encountering an error on the second call. Here is what my function does: let content = '' let size = 100 let from = 1 function result(size, from, callback) { ap ...

Ensuring precise accuracy in JavaScript; transforming 0.5 into 0.5000

My current challenge involves converting every fraction number to n decimal places in JavaScript/Node.js. However, I've encountered a roadblock as it appears impossible to convert 0.5 to 0.5000. This discrepancy is causing my test cases that anticipat ...

What is the best way to deliver flash messages using Express 4.0?

Currently, my web application requires authentication, and I am encountering an issue with the signup page. If a user tries to sign up with an email that is already in the database, I want to display an error message. Here is the code snippet I am using on ...

Tips on utilizing the useState hook for storing numerous key objects?

Currently, I am working with a candlestick chart for a cryptocurrency that displays data over different timeframes such as 1 minute and 30 minutes. Below is the code snippet that sets the initial state to show a 1-hour chart when a user first visits: const ...

Download a file on button click using JavaScript with data extracted from the DOM

I am looking to create a download feature where a user can click a button on the webpage, triggering a JavaScript method to capture the contents of a DOM element and prompt the user for a download. After successfully capturing the DOM element in a JavaScr ...

Is it possible to view the object sent from AJAX to PHP in PHP using a debugger?

I'm facing an issue where I am making an AJAX call to a PHP file, sending a JSON object as a parameter from JavaScript. The PHP file is supposed to perform some logic with the object and return it using json_encode('whatever');. However, the ...

What is the best way to transfer variables between two Vue files?

How can I transfer a variable between two Vue files? Hello, in my SendCode.vue file, I have a variable named NewEmail that I would like to use in another file called changePass.vue. Is there any way to do this? Can someone offer assistance? Thank you</p ...

Avoid activating jQuery functions based on certain screen widths for menu/navigation system

Recently, I've delved into the world of jQuery and attempted to create a simple menu system. The menu is designed to expand its submenu when hovering over the list item at screen widths larger than 480px, and to expand when clicking on the list item a ...

What is a clear indication that a <div> is filled with text?

Picture a scenario where a website contains an element that needs to be filled with random text using JavaScript. Once the div is completely filled, it should reset and begin again. It may sound odd, but the question is: how will the JavaScript determine w ...

Populating JQuery autocomplete using a PHP array

As a beginner in the world of JavaScript and JQuery, I have been scouring the internet for hours trying to find a solution to my query. My goal is to populate a JQuery autocomplete feature using an array that I have created in PHP. Here is a glimpse of the ...

Obtain the key by using the JSON value

I am seeking to identify the recursive keys within a JSON Object. For instance, consider the following JSON Object: { "Division1" : { "checked": true, "level": 1, "District1-1": { "checked": true, "level ...

Receive regular updates every week for an entire month using Javascript

How can I calculate the number of check-ins per week in a month using Javascript? I have been unable to find relevant code for this task. Specifically, I am interested in determining the total count of user check-ins on a weekly basis. For example, if a u ...

Choose or deselect images from a selection

I am currently working on a feature for an album creation tool where users can select photos from a pool of images and assign them to a specific folder. However, I'm facing difficulty in selecting individual photos and applying customized attributes t ...

Pressing the button will allow you to select and copy the text within the

I am looking to incorporate a mock-chat feature into my website. The concept is to type something on the website, then click a button next to it which will move the text to a frame above. I attempted this using a textarea and even found a code for selectin ...

"After completing the survey form, the User Details form is displayed upon clicking the submit button

In my Quiz, each question loads on a separate page with clickable options. Some questions may have multiple answers, including an "Others" option. At the end of the quiz, users need to fill out a form. Although I've created a survey form, I'm fa ...

Exploring the functionality of the MediaPicker property editor within a custom property in Umbraco

I am currently working on a custom property editor that utilizes the media picker. My controller code is as follows: angular.module("umbraco").controller("My.MediaCropperController", function($scope, dialogService) { $scope.mediaPicker = { ...