Numerous asynchronous requests

I'm trying to figure out why the application keeps making multiple ajax calls.

Check out this directive:

gameApp.directive('mapActivity', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            scope.$watch(function(scope) {
                angular.element('.click#1').addClass('dotted').html($("<img src='images/dot.png'>"));
                var j = null;
                for(var i = 1; i <= 4; i++)
                {
                    $.ajax({
                        type: 'GET',
                        url: 'lib/terrain.php',
                        dataType: 'html',
                        data: {i: i},
                        success: function(data) {
                            var randomRuta = Math.floor((Math.random() * 100) + 1);
                            angular.element('.click#'+randomRuta).addClass('monster').html($("<img src='images/blackdot.png' title='"+data+"'>"));

                        },
                        error: function(xhr, ajaxOptions, thrownError) { alert(thrownError); }
                    });
                    j=i;
                }  
                angular.element('.click').click(function() {
                    if(angular.element(this).hasClass('monster'))
                    {
                        if(confirm('Vill du anfalla monster?'))
                        {
                            alert("Du vann");
                            angular.element('.click.monster'+j).empty();
                            angular.element('.click.monster').removeClass('monster'+j);

                            angular.element('.click.dotted').empty();
                            angular.element('.click.dotted').removeClass('dotted');
                            angular.element(this).addClass('dotted');
                            angular.element('.click.dotted').html($('<img src="images/dot.png">'));
                        }
                    }
                    else
                    {
                        angular.element('.click.dotted').empty();
                        angular.element('.click.dotted').removeClass('dotted');

                        if(!angular.element(this).hasClass('dotted'))
                        {
                            angular.element(this).addClass('dotted');
                            angular.element(this).html($('<img src="images/dot.png">'));
                        }
                    }
                });
            });                     
        }
    };
});

It seems like the ajax call is being made twice instead of just four times inside the loop. This inconsistency is causing issues in the functionality of the application.

Below is my controller configuration:

var gameApp = angular.module("gameApp", ['ngRoute','ngSanitize']);

// code for service and additional app configurations

Here is a snippet of the HTML code where the directive is used:

<div ng-controller="gameCtrl">
    <table ng-bind-html="safeHtml()" map-Activity>
    </table>
</div>

If anyone has any insights or suggestions on how to resolve this issue, it would be greatly appreciated!

Answer №1

It appears that the function makeTableFrom is being called (to build HTML for manipulation) after the response from $http.post("lib/action.php") is received. The link function of the mapActivity directive, however, runs much earlier than this response. Therefore, the element that angular.element('.click#1') refers to does not currently exist. By enclosing it in a scope.$watch, you are ensuring that it runs every time there is a change on the scope. The line

$scope.result = makeTableFrom(data);
definitely causes a change on the scope, meaning that once the response is received, there will be an element matched by angular.element('.click#1') (created by makeTableFrom). The issue is that the code within scope.$watch executes at least once before the response arrives. To address this, you either need to reconsider the entire approach or take a quick fix by checking if the elements exist before manipulating them:

scope.$watch(function(scope) {
    if(angular.element('.click#1').size() > 0) {
        ...
    }  
}

Furthermore, the reason why the idea of using scope.$watch is flawed is because it will also run in the future whenever you modify the scope (`$scope.foo = 'bar`).

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

Utilize the Multer file upload feature by integrating it into its own dedicated controller function

In my Express application, I decided to keep my routes.js file organized by creating a separate UploadController. Here's what it looks like: // UploadController.js const multer = require('multer') const storage = multer.diskStorage({ dest ...

Click anywhere outside the sidemenu to close it

I want the menu to behave like the side menu on Medium. When the side menu is open and the user clicks outside of #sidebar-wrapper, the side menu should close. Currently, I have to click the toggle X to close the menu. html <a id="menu-toggle" href="# ...

Receiving the error "Undefined chart type" when using $q.all with Google Chart API Promise

I am currently working on implementing angular-google-charts using the $http service to retrieve data and display it on charts. I found a helpful tutorial on this blog post: since the GitHub README for angular-google-charts lacks examples of backend data ...

JavaScript's "for of" loop is not supported in IE 11, causing it to fail

Here is a piece of code I'm using to select and remove a d3.js node: if (d.children) { for (var child of d.children) { if (child == node) { d.children = _.without(d.children, child); update(root); ...

Retrieve the value of angular js http.get when the response is in text format

I am working with an angular js controller that has a http get method. I need to retrieve the response value of the http request. In the headers, I have included: -H "Content-Type: application/json" -H "Authorization: Basic YGDJSDJH4564363YTESNSBS4=" The ...

Using Polymer to automatically update the DOM when a JSON file is modified

I am currently developing a modal window to add data to a JSON file and then display that data in the DOM. The issue I'm facing is that while the data gets saved to the file successfully, it doesn't reflect immediately on the DOM. The technology ...

Determine if a class is odd or even in Angular by utilizing ng-click

Trying to alternate classes on elements in an ng-repeat loop based on whether they are even or odd... <div ng-click="displayHTML(content)" ng-class-odd="'title'" ng-class-even="'html'" ng-repeat="content in name.name"> {{cont ...

Implementing Github Oauth2 in a Rails server independent from a chrome extension

Looking to implement Github Oauth2 from my chrome extension, but rather than using chrome.identity.launchWebAuthFlow I want to handle it through my server. This way, I can avoid exposing my client ID and Client Secret in the javascript of the extension. My ...

Tips for effectively highlighting search text within HTML content without causing any issues

I am in search of a solution that can assist me in searching for specific terms within an HTML string while also highlighting them. I have the ability to remove the HTML content from the string, but this poses the problem of losing the context of the origi ...

Using AngularJS's "debounce" feature with ngBind

When using ngModel, you can specify options like ng-model-options="{ debounce: 1000 }" Is there a similar feature available for ngBind or {{}} ? I am currently binding data to a div element using ng-bind, and by default, Angular.js updates the div as so ...

What is the best way to showcase my React App.js in an HTML document?

Is there a way to display my React app file (App.Js) within my Index.html file? <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/fav ...

Struggling with implementing the use of XMLHttpRequest to transfer a blob data from MySQL to JavaScript

I have a blob stored in my local WAMP64/MySQL server that I need to retrieve and pass to an HTML file using XMLHttpRequest. I know I should set responseType="blob", but I'm not sure how to transfer the blob from PHP to JavaScript in my HTML file. Any ...

Retrieving URL parameters within an API route handler in Next.js

Within my client component called GetUserInfoButton, I initiate a GET request using the URL format of http://localhost:3000/test/users/[id]. The [id] in this URL is represented by an alphanumeric sequence similar to MongoDb. My intention within the file a ...

Issue: $injector:unpr Unrecognized Provider: itemslistProvider <-

I've spent several days debugging the code, but I can't seem to find a solution. I've gone through the AngularJS documentation and numerous Stack Overflow questions related to the error, yet I'm still unable to identify what's caus ...

Determine whether a value contains a minimum of two words or more using JavaScript

When users input their names into a field and submit it, I want to make sure that I receive both their first and last names. In order to do this, I need to check if the value contains at least two words. However, the current code I am using does not seem ...

issue with logging in, token verification failed

My current project involves creating a login system with authorization, but for some reason the token is not being transferred properly. const path = require('path'); const express = require('express'); const bodyParser = require(' ...

Looking for assistance in streamlining JavaScript for loops?

I am currently working on a project involving a random image generator that displays images across up to 8 rows, with a maximum of 240 images in total. My current approach involves using the same loop structure to output the images repeatedly: var inden ...

Is there a problem with renaming files using the multer module's filename options?

I can't figure out why this isn't functioning as intended. The file upload feature is operational, but the generated name consists of a long string like 04504a8b6c715f933110c8c970a8f6ad. What I need is for the filename to include the original nam ...

showing errors in case the username does not match the specified pattern

As I work with symfony, one of the challenges is displaying errors when the username does not fit the specified pattern. How can this be achieved? {{ form_widget(form.username, {'attr':{'pattern': '[a-zA-Z]*'} }) }} ...

What is the best way to implement nested iterations in Jade?

ul li a(href='') menu1 li a(href='') menu2 ul li a(href='') sub-menu2 li a(href='') menu3 ul li a(href=&apos ...