Angular looping does not display data as expected

I am trying to display data from a JavaScript for loop inside a modal using ng-repeat for detailed information. Below is the snippet from my .js file:

$http.get('.....').then(function(response){
                $scope.coba = response.data;
                $scope.totalItems = $scope.coba.length;
                for (var i = 0; i <= $scope.totalItems ; i++) {
                  $scope.coba2 = JSON.parse($scope.coba[i].additionaldata_pay);
                  return i;
               };

However, when I execute it, the details do not show anything, as shown in this screenshot:

https://i.sstatic.net/qkHnN.png

Here is my modal in .html:

<h4 class="modal-title">Detail </h4>
                        </div>
                        <div class="modal-body" ng-repeat="item2 in coba2">
                            <p>{{item2.label}}</p> <p>{{item2.value}}</p>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                        </div>

The response of scope coba in ARC contains the following fields:

"customerid": ".....",
"paydate": ".....",
"amount": ".....",
...

Answer №1

To optimize your code, ensure that your loop is using additionaldata_pay rather than scope.coba. Also, make sure to check the array condition after parsing your string. Here's a revised version of the code:

angular.module("mod",[]).controller("contr",["$scope", function($scope)
{
  var response={}; 

   response.data = {object1:'', additionaldata_pay:[{lable:'1',value:'1'},
            {lable:'2',value:'2'}]};         
  $scope.coba = response.data;// it should be an array
     if(!angular.isArray($scope.coba.additionaldata_pay)) 
        {
          return false;
        }
      $scope.totalItems = $scope.coba.additionaldata_pay.length;
      $scope.coba2=[];
      for (var i = 0; i <= $scope.totalItems ; i++) {
          $scope.coba2.push($scope.coba.additionaldata_pay[i]);
          };
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="mod" ng-controller="contr">
   <div class="modal-body" ng-repeat="item2 in coba2">
                        <p>{{item2.label}}</p> <p>{{item2.value}}</p>
                    </div>
</div>

EIDT:

  • response.data must be an array or support parsing as an array if it's a string
  • Your for loop should depend on an array instead of an object. It is recommended to use the for loop for $scope.coba.additionaldata_pay instead of $scope.coba
  • Ensure you are checking the array index or object name to display in ng-repeat.

Answer №2

When dealing with an array of objects like coba2, consider using the following approach:

        $http.get('.....').then(function(response){
            $scope.coba = response.data;
            $scope.totalItems = $scope.coba.length;
            $scope.coba2 = [];
            for (var i = 0; i <= $scope.totalItems ; i++) {
            $scope.coba2.push(JSON.parse($scope.coba[i].additionaldata_pay));
         };

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

What is the most effective method in React JS to achieve real-time results with every keystroke by making REST calls to the server?

We are dealing with a huge database and the task at hand is to display results as the user types them in the search box. Preloading queries to attempt matching is out of question due to the enormity of our data. Currently, we make a server request with th ...

Sending an empty object from postman in form-data to a node.js server is causing issues

Despite searching extensively, I have yet to find a solution to my issue that has been asked numerous times before. index.js file const express = require("express"); require("dotenv").config({ path: ".env", }); const PORT = ...

How can Node.js identify the page where visitors entered, the page they are currently on, and the page

After creating a Node server with socket.io, I'm interested in tracking the entry, current, and exit pages for each user. My plan is to store this information within the user's session for future reference. I'm currently stuck on how to obt ...

Updating data from an ajax call in chart.js can be done with a few simple steps

I have successfully generated a graph using data from an ajax call in a php file. Now, I want to enhance this graph by allowing users to select a specific customer from a drop-down list (chg_customer) and display the corresponding count on the chart. Altho ...

Switching over to the latest version of Material-UI, v1.x.x

Currently, my app relies on Material-UI v0.17.0 which is not compatible with React v16.0.0. In order to make it work, I need to upgrade to Material-UI v1.0.0. I came across a migration tool here, but it only updates import statements. Many props have chan ...

React: Resolving issue of state becoming outdated after fetching data through a network request in the useEffect hook. Stale state no

As I work on updating and referencing the state field hasError within the initialization function of my component, it's crucial for me to control whether a redirect occurs after successful initialization or if an error is displayed. Here's a sum ...

Deciphering Google location data using JavaScript

It appears that this code is not functioning properly for unknown reasons let url = "https://maps.googleapis.com/maps/api/place/search/json?"; url += "location="+lat+","+lng+"&"; url += "radius=500&"; url += "types=&"; url += "name=&"; url ...

What is the best way to iterate through an object and display each item as <li></li> within another <li>?

After retrieving a specific object from an express endpoint and seeing it on the console, I need to figure out how to map it in order to display a jsx that resembles this <li>keys</li> : <li>values</li> For example: Company: DML ...

Send form using AJAX with a callback function

I need help figuring out how to submit a form when a captcha is clicked. I attempted to use my own jQuery function, but unfortunately it's not working. Could someone please take a look at my code and let me know what's wrong with it? Javascript ...

Only the initial setInterval function is currently active, despite multiple being set simultaneously

I am currently working on developing a webpage with a dynamic background featuring moving clouds. The code I have written for this project utilizes jQuery as shown below. browserWidth = 0; browserHeight = 0; clouds = 4; cloudSpeed = 50; $(function() { ...

Delete the tag that comes before

Is there a specific tag like: <p id="name" onclick="javascript:var ele=context(this);">sumtext here</p><br> <p id="name" onclick="javascript:var ele=context(this);">newtext here</p><br> <script ...

Turn off Node.js Caching for Good

My Node.js website seems to be stuck using a cached version even after updating the code and using the -w option. I need to figure out how to disable caching with Forever in Node.js and completely uninstall it. I found this answer that confirms it caches: ...

The fade animation on my modal is causing issues in Windows 10

Hi everyone, I've created a bootstrap modal with the fade CSS class. If you want to see what I'm referring to, you can check it out here: MyProject Let me break it down for you step by step. Initially, this page functions as follows (it's ...

Error alert: The function is declared but appears as undefined

Below is the javascript function I created: <script type="text/javascript"> function rate_prof(opcode, prof_id) { $.ajax({ alert('Got an error dude'); type: "POST", url: "/caller/", data: { ...

What steps can I take to get a border functioning correctly on my website?

For my friend's birthday, I am designing a website that resembles a greeting card. The layout consists of text in the center and an image of a birthday cake. To give it a card-like feel, I want to create a border around it. Although I know how to adju ...

Transforming the button behavior with jQuery

I have encountered a situation where I am working with code in Twig. {% if followsId == null %} <div id="followUser" class="follow" data-userId="{{ profileUserData.id }}" data-currentUserId="{{ loggedUserData.id }}" data-action="follow"> ...

Issue with importing a library into a Next.js component

I seem to be facing an unusual issue with my Nav component. Although I am able to import various items in my other components without any problems, for some reason, I cannot import anything into my Nav component. import { useState, useEffect } from "r ...

Rails: jQuery - page refreshes unexpectedly during event execution

After successfully implementing a jQuery script for my custom dropdown menu on a standalone webpage, I encountered issues when integrating it into my Rails application. I am unsure if the problem is related to Turbolinks or if there is another underlying c ...

Is there a way to display "no results" on the page when the search field is empty, yet still render new results asynchronously while searching?

I am implementing a feature where buttons are dynamically rendered on the page based on user input. Each time the user types a letter, a new set of buttons is displayed on the page using an obj.content that contains the string being typed. Although this fu ...

Utilizing ng-grid to pass variables within cellTemplate

My ng-grid is connected to a SharePoint list, but I'm facing an issue where the list returns an ID number instead of the user name when populating a field with a user name. To solve this issue, I have created a function that converts the ID to a user ...