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

By pressing the "showMore" button, the page dynamically pulls in a json list from a file

Currently, my focus is on a dropwizard-Java project. My task involves retrieving and showcasing the first 10 items from a json list in a mustache view. If the user clicks on the "show more" link, I should retrieve the next 10 elements from the list and d ...

Jade not responding to AngularJS click directive function

This tutorial is inspired by the MEAN Stack demo: Mongo, Express, AngularJS, and NodeJS I am attempting to incorporate a 'delete' method into my controller in the Jade template as shown below: characters.jade script function CharactersCont ...

Clicking on a class within a single tag can be selected using

Currently facing a seemingly trivial issue that I can't quite figure out. I have a jQuery function that selects the class of a tag when clicked, but the problem is that it also selects every other tag beneath the clicked tag in structural order. Howev ...

Angular Controller issue: 'MainCtrl' variable is not recognized as a function, it is showing as undefined

Out of the blue this afternoon, I encountered a puzzling AngularJS error: Argument 'MainCtrl' is not a function, got undefined While my Chrome browser still runs smoothly without any issues, I am struggling to identify the differences that cause ...

Create a list with interconnected input fields for duplication

I'm new to javascript and I have a question. I'm working on duplicating a list that has input fields for each option. The duplication is working fine, but the associated input fields are not showing up in the duplicated list. Additionally, I woul ...

AngularJS: The creation of a unique custom filter in Angular causing an infinite loop issue

I have implemented a custom filter called 'partition' in my filter.js file within my Ionic application. However, when I attempt to use it in the template, I encounter a $rootScope error: Error: [$rootScope:infdig] http://errors.angularjs.org/1.2 ...

Having trouble receiving values sent through AJAX POST requests to PHP

Can anyone help me figure out why my AJAX POST method is not sending the specific section of my URL string to my PHP file? I've checked everything and can't seem to find where the issue lies. When I var_dump the POST variable in my PHP file, it s ...

How to adjust the timezone settings in PHPMyAdmin on a shared server platform

I'm having trouble changing my timezone to India on my shared server database. I've tried everything but can't seem to get it to work. My website is built using PHP Codeigniter The contact us page on my site saves all inquiry details to my ...

Ways to integrate npm dependencies into your Cordova plugin

Currently working on implementing a Cordova plugin called core-cordova found in this repository. This particular plugin has a dependency on another NPM package. The issue arises after installing the plugin in my app using: $ cordova plugin add @aerogears ...

Resuming AJAX requests after being aborted

Hey everyone, I'm curious to know if it's possible to resume interrupted ajax requests. I have an array of ajax calls stored as defferreds like this: var defferreds = []; defferreds.push( $soap.ajax({ type: "POST", dataType: ...

This marks my initial attempt at developing an Angular project using Git Bash, and the outcome is quite remarkable

I have a project named a4app that I am trying to create, but it seems to be taking around 10 minutes to finish and is showing errors. The messages displayed are quite odd, and I suspect there may be an issue with the setup. I have not yet used the app that ...

Unable to trigger the show_popup function by clicking the button

Why won't this piece of code function as expected? <script src="web_push.js"></script> <body> <button onclick="show_popup()"> Button </button> </body> The content of web_push.js file is shown below ...

The antithesis of jQuery's .parents() selector

I am currently developing a userscript for a webpage with an old-fashioned design consisting mainly of tables. My goal is to access a long table of fields so that they can be filled in automatically by the script. To simplify, the structure is as follows: ...

AngularJS chatbox widget for interactive communication

Currently, I am in the process of developing the back-end for a web application utilizing angularJS. One of the key features is allowing users to communicate with each other through a pop-up chat box similar to those found in Gmail or Facebook. My goal is ...

Exploring a one-dimensional nested array in order to make updates to the higher level nodes

I have a 1D nested array: nestedArr: [ { id: 1, parentId: null, taskCode: '12', taskName: 'Parent', duration: 0, assignee: '', crewCount: 0, startDate: null, endDate: null, dependencies: []}, { id: 2, parentId: 1, taskCo ...

What is the best way to add a color swatch image using Javascript?

I'm facing a challenge in Shopify where I need to assign corresponding background images to color swatches. Currently, my icons are set up with the correct links for each color, but they are missing their respective images, similar to this example. I ...

The click event for jQuery is failing to trigger on every link

Currently, I'm in the process of creating a "collapse all" button for the Bootstrap 3 collapsible plugin. It appears to be functioning correctly, but only when there is just one collapsible on the page. Once I add another one, the method only works on ...

Is it possible to convert checkbox values from a form into a JSON format?

HTML snippet : <form class="form-horizontal" id="addpersons" style="padding:20px;"> <fieldset class="scheduler-border"> <!-- Form Title --> <legend class="scheduler-border">Information</legend> <!-- First Name input-- ...

Node.js equivalent of Java's byteArray

I have a Node.js REST API with images being sent from a Java application as byte arrays. Here is an image Below is the string representation of the image in byte array form: [B@c75af72 I need to decode this byte array to verify if it is indeed an ima ...

Tips for successfully passing array index as an image source in Vuejs with v-img?

Hi there! I'm currently attempting to cycle through an array of URLs and insert them into the src attribute. I'm struggling with the correct syntax to accomplish this task. Would you be able to lend a hand? I have an array named DataArray that co ...