Troubleshooting: AngularJS ng-repeat not rendering JSON data

I have successfully retrieved JSON data from a database using PDO in Angular. The data is being returned as expected when I encode it to JSON. However, I am facing an issue with displaying the data using ng-repeat in Angular.

Although the div elements are showing up, the post.time value is not being displayed.

HTML

<html ng-app="dataVis">
    . . .
    <body ng-controller="GraphController as graph">
        <div ng-repeat="post in graph.posts track by $index">
            {{post.time}}
        </div>
    </body>
</html>

JSON data

[
    {
        "time": "1340",
        "postId": "282301",
        "likes": "2"
    },
    {
        "time": "1300",
        "postId": "285643",
        "likes": "0"
    }
] . . . (etc)

JS

(function () {

  var app = angular.module('dataVis', []);

  app.controller('GraphController', ['$http', function ($http) {
    var graph = this;
    graph.posts = [];
    $http.get('/query-general.php').success(function (data) {
      console.log(data); // returns JSON data
      graph.posts = data;
    });

  }]);

}());

In my initial code, I did not include track by $index, but after encountering a duplicate error, I added it.

I am seeking assistance in properly displaying the JSON data on the HTML page using ng-repeat in Angular. Any help would be greatly appreciated!

Answer №1

Before passing data to $scope.graph.posts, make sure to declare the $scope.graph variable first.

$scope.graph = {};
$scope.graph.posts = data;

To see a working example, check out this JSFiddle http://jsfiddle.net/RkykR/294/

This is how the HTML code looks:

<h3>Ng-Repeat example</h3>
<div ng-app ng-controller="MyCtrl">

<table>
    <thead>
        <tr><td>time</td>
            <td>postID</td>
    <td>likes</td>
        </tr>
        </thead>
    <tbody>
                <tr ng-repeat="item in graph.posts"><td>{{item.time}}</td>
            <td>{{item.postId}}</td>
    <td>{{item.likes}}</td>
        </tr>
    </tbody>
</table>
</div>    

And here is the JavaScript code:

   var data = [
    {
        "time": "1340",
        "postId": "282301",
        "likes": "2"
    },
    {
        "time": "1300",
        "postId": "285643",
        "likes": "0"
    }
];

function MyCtrl($scope) {
    $scope.graph = {};
    $scope.graph.posts = data;
}

Finally, the CSS styling for the table:

table {
    padding:5px;
    width:500px;

}

table td {
    border: 1px solid gray;
    padding:3px 0;
    text-align:center;
}

table thead td {
    font-weight:bold;
}

Answer №2

Have you attempted to access the properties in json by using array notation? This is necessary because the properties are named with quotes such as "time" instead of just time.

<td>{{item["time"]}}</td>
<td>{{item["postId"]}}</td>
<td>{{item["likes"]}}</td>

Answer №3

After some investigation, I discovered the root cause of the problem. It turns out that there were comments present in my PHP files outside of the designated PHP tags. This caused issues when Angular attempted to retrieve JSON data from the PHP page as it also fetched the unwanted comments. Grateful for the assistance provided throughout this troubleshooting process.

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

Testing API calls with ReactJS

I'm diving into Reactjs development and have encountered a challenge. I created an App that makes API calls to https://jsonplaceholder.typicode.com/users. However, when testing the API call, I ran into issues. In addition, I built a simple WebApi pro ...

What steps can be taken to ensure that a WebSQL query does not return negative

Here's the code snippet I am currently using: function decrementCart(quantity, id){ db.transaction(function(tx){ tx.executeSql("UPDATE cart SET quantity=(quantity -1) WHERE id=?", [id]) ...

Stream JSON data to a file with Node.js streams

After reading this article, I decided to utilize the fs.createWriteStream method in my script to write JSON data to a file. My approach involves processing the data in chunks of around 50 items. To achieve this, I start by initializing the stream at the be ...

"Enhancing website performance with JavaScript by leveraging DOM innerHTML scrollHeight

Here is a two-part question I have: The first part of the question: test A: t1 = new Date().getTime(); for (i=0; i<205; i++) { document.getElementById("divTest").innerHTML = sText; } t2 = new Date().getTime(); ...

Oops! Could not compile due to a syntax error: Invalid assignment expression on the left-hand side

I am currently developing an application that requires me to retrieve data from the backend containing a userdetail object. In my code, I need to set a current accessToken for the userdetail object: useEffect(() => { if (session?.user && ...

Issue encountered during npm install process

Encountered an error while running the npm install command. angular#1.2.1 bower_components\angular npm ERR! peerinvalid The package karma-requirejs does not satisfy its siblings' peerDependencies requirements! npm ERR! peerinvalid Peer <a hre ...

Change the size of the individual cells within JointJS

I have some code for a jointjs demo that includes basic shapes on a paper. I am looking to adjust the size of the shapes or highlight them when clicked on or when the cursor moves over them. var graph = new joint.dia.Graph; v ...

How to assign various column values to a PHP array in JSON format from a MySQL database

I am struggling with making a JSON Ajax request and receiving an array in return. After browsing through multiple questions, I came across this code snippet that I edited to fit my problem: var hej[]; function ajax_search(){ $.getJSON('test.php ...

Ways to define properties in backbone entities

As I work on my app using backbone, I'm encountering a challenge that might be due to a misunderstanding on my part. I am trying to set specific attributes like titles while also having default values in place. However, it seems that the custom attri ...

After activating the rewrite feature on Tomcat valve, JavaScript is loading twice

I've implemented the Tomcat rewrite valve in my single-page application to direct all requests, except for static resources, to my index.html file. Here is what my rewrite.config looks like: RewriteCond %{REQUEST_URI} (?!.*\.(?:jpg|png|css|js|js ...

PHP implementation for a static header layout

I am interested in learning how to update content without refreshing the header. I have created a simple example below. Header.php <html> <head> </head> <body> <ul> <li><a href="index.php" ...

Deciphering a JSON array in PHP

After retrieving a decoded JSON array from the Facebook API, here is how it looks when printed: $Myposts = json_decode($response->getBody()); var_dump($Myposts); It displays various messages with their corresponding created times and IDs. Now, I want ...

Perform calculations for product and sum when button is clicked

I received the following task for an assignment: Develop 3 functions along with a form. The first function should execute upon button press and utilize the other 2 functions. These two functions are supposed to compute the sum of two numbers and the ...

What is the best way to incorporate AJAX with Node.js?

After testing the Hello world program with Node.js, I can confirm that it is working perfectly. Here are the file details: index.html socket.js To run in command prompt: node socket.js I also experimented with ajax calls in Node.js using the same hel ...

What is causing the issue with object to JSON conversion not functioning correctly in this particular scenario with Spring MVC?

I have a specific URL that I need to execute: http://localhost:8080/FitiProject/student. The response that I'm expecting should be a JSON string containing the data of a Student object. Below is the code that I am using: package spring.controllers; ...

Using JavaScript to create circular shapes on canvas with paint circle

I need assistance in JavaScript to create a circle and update it while removing the previous one. My current code is: <html> <head> <style> body { margin: 0px; padding: 0px; } </style> </head> <body> <ca ...

I encountered a parsing issue while trying to compile my Vue project

Issue: The component name "Header" should always consist of multiple words. Fix: Change the component name to a multi-word format according to Vue standards (vue/multi-word-component-names). ...

NG build error: Module parsing failed due to an unexpected token - no updates made

Two days ago, out of nowhere, we started encountering build errors during deployment using GitLab CI. No alterations have been made to the build scripts, and none of the versions of NPM, NG, or Angular have been modified. The same compilation commands cont ...

Issue encountered while selecting the Electron app menu item

I encountered an error when clicking on a menu item: Any suggestions on how to resolve this issue? Here is the snippet of code that seems to be causing the problem: Main.js const { Menu } = require('electron') const { createNewFile } = require ...

Utilize jQuery and PHP to populate an HTML Select Field with data retrieved from a MySQL Database in JSON format

I am exploring how to Transfer Database Data into an HTML Dropdown Selection Field using jQuery. I came across a useful example that seems promising. Although I am new to jQuery and JavaScript, I am eager to learn. My goal is similar to the approach descr ...