ng-repeat not functioning properly with data defined in XMLHttpRequest

I have a problem with my HTML and AngularJS code. Initially, I defined the list in my controller which worked fine:

<li ng-repeat="a in idmasVesselstableList"><a>{{a.table_name}}</a></li>

And here is how I set up the controller:

angular
  .module('myApp')
  .controller('idmasCtrl', ['$scope', function($scope) {

      $scope.idmasVesselstableList = [{"table_name":"api_574_structural_thickness"},{"table_name":"api_574_structural_thickness_rev_history"},{"table_name":"cml"},...];

  }])

This displayed the list correctly. However, when I tried to define the list within an XMLHttpRequest, it did not work as expected. Here is the code snippet:

angular
  .module('myApp')
  .controller('idmasCtrl', ['$scope', function($scope) {
      xmlhttp = new XMLHttpRequest();
      xmlhttp.open("GET","/getvesselstablelist.js", true);
      xmlhttp.onreadystatechange=function(){
         if (xmlhttp.readyState==4 && xmlhttp.status==200){
           string=xmlhttp.responseText;
           $scope.idmasVesselstableList = JSON.parse(string);
         }
       }
  xmlhttp.send();
}])

If anyone has any suggestions on how to generate the list correctly inside the XXMLHttpRequest on readystatechange, I would greatly appreciate it.

Thank you for your assistance.

Answer №1

To begin, utilizing the Angular $http service for AJAX requests is recommended. Here is an example using $http.get():

$http.get("/getvesselstablelist.js").then(function(response){
   $scope.idmasVesselstableList = JSON.parse(response.data);
});

If you are unable to use the $http service for some reason, you can manually update the scope by calling $scope.$apply within your XMLHttpRequest callback function. This is necessary to inform Angular that changes have been made outside of its normal execution context.

xmlhttp.onreadystatechange=function(){
   if (xmlhttp.readyState==4 && xmlhttp.status==200){
     var string = xmlhttp.responseText;
     $scope.$apply(function(){
       $scope.idmasVesselstableList = JSON.parse(string);
     });
  }
}

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

`Is there a way to dynamically update a nested field object in Mongoose without updating the entire object?`

const userProfile = new Schema({ name: { type: String, default: null }, contacts: { mobileNumber: { countryCode: { type: String, default: null }, digits: { type: String, default: null } }, email: { type: String, default: null }, facebook: { ...

Guide to displaying PHP output in a format suitable for plotting

I'm currently working on plotting PHP output from a MySQL database using . The desired format for the output should look like this - var data = [ { x: ['giraffes', 'orangutans', 'monkeys'], y: [20, 14, 23], ...

Is it possible to compile TypeScript modules directly into native code within the JavaScript data file?

I am seeking a way to break down an app in a TypeScript development environment into separate function files, where each file contains only one function. I want to achieve this using TS modules, but I do not want these modules to be imported at runtime in ...

What is the best way to convert this JavaScript iteration function into jQuery?

I recently encountered an issue with my JavaScript function that returns a list of elements with the class ".youtube", loops through them, and calls another function. The JavaScript logic is flawless, but I wanted to convert it into jQuery for better reada ...

Tips for Customizing the Appearance of Material UI Select Popups

My React select component is functioning properly, but I am struggling to apply different background colors and fonts to the select options. https://i.stack.imgur.com/kAJDe.png Select Code <TextField fullWidth select size="small" nam ...

I am facing an issue where the text I included is not appearing on the website that

While developing a React version of my online portfolio, I encountered an issue. Once deployed on GitHub pages, the text on my landing and contact pages disappeared. Despite removing the background image thinking it might be hiding the text, the issue pers ...

Pressing the button updates the value in the input field, but the input field continues to

I need some assistance with my e-commerce platform. I am trying to implement a button that adds items to the shopping cart, but I'm encountering an issue where the value in nbrSeats (my list of values) changes in the data, yet the input field displays ...

Warning: Nodemailer has issued a deprecation warning regarding the outdated `punycode` module

Looking to automate daily email sending through a Gmail account, I have been experimenting with nodemailer and crafted this simple test code: const fs = require('fs'); const path = require('path'); const nodemailer = require('nodem ...

Can someone explain why my button icons are not aligning to the center properly?

I have a small issue with the icons I pulled from react-icons - they appear slightly raised within the buttons. How can I position them in the middle? That's my only query, but I can't post it alone due to mostly having code in my post. What an ...

React automatic scrolling

I am currently working on implementing lazy loading for the product list. I have created a simulated asynchronous request to the server. Users should be able to update the page by scrolling even when all items have been displayed. The issue arises when ...

Best practice in Angular: Initializing data in a service during start-up

Looking to create an angular service that collects data upon "start-up" and forms an array that remains unchanged throughout the application's lifespan. Avoiding the return of the http request promise is a priority, even though caching the result woul ...

How can I use Angular forEach to retrieve both the name of a JSON key and its corresponding

Is there a way to retrieve both the key name and value of a JSON object in Angular using the forEach method? var institute = { "courses": [], "user_type": 3, "institute_name": "sd", "tagline": "sd", "overview": "sd", ...

The outcome of Contains function is coming back as negative

Recently, I was working on a project that I cloned from GIT, which involved a bot. However, I encountered an issue where the 'contains' function used by the bot was not functioning properly. After conducting some research using Google, I discove ...

Is it possible to send an array value from JavaScript Ajax to PHP and then successfully retrieve and read it?

As a newcomer to PHP, I am facing a challenge in saving multiple values that increase dynamically. I'm passing an array value using the following method from my JavaScript code. $(".dyimei").each(function(i,value){ if($(this).val()=="") ...

Tips for stopping the textarea from moving around as you type and avoid it hitting the bottom of the page: Utilize JQuery and

As I type into the auto-sizing textarea, the text runs to the bottom of the page and causes it to dance uncontrollably with each key press. This forces me to constantly scroll down to see what's happening. How can I prevent this page dancing and keep ...

Submit data in the manner of a curl request

Instead of using a curl command to push a file to a web server, I am attempting to create a simple webpage where I can select the file and submit it. Here is the HTML and JavaScript code I have written for this purpose: <html> <body> <i ...

Using multiple html files with ui-router's ui-view feature

Is it possible to create a complex UI using multiple HTML files with ui-view in AngularJS? I am trying to achieve a layout similar to this: I attempted to implement something on Plunker, but it seems like I'm struggling to grasp the underlying concep ...

Step-by-step guide on uploading a template in unlayer-react-email-editor

<EmailEditor ref={emailEditorRef} onReady={onTemplateReady} /> const onTemplateReady = () => { try { const templateJson = htmlToJSON(savedData?.email?.content); console.log({ templateJson }); emailEditorRef?.current?.editor?. ...

Execute the script using ajax

Is it possible to execute JavaScript within an AJAX request? I attempted to include some JavaScript code in the PHP file that was called by an AJAX command. The purpose of this script was to modify an HTML attribute on the parent page. However, it did not ...

Solving compatibility problems with jquery AJAX requests on multiple browsers

searchCompanyExecutives: function(criteria, callback) { var params = $j.extend({ type: "GET", data: criteria, url: "/wa/rs/company_executives?random=" + Math.floor(Math.random() * (new Date()).getTime() + 1), ...