What is the best way to display Json data using ng-repeat in AngularJS?

Is it possible to display JSON data in AngularJS using ng-repeat? I am trying to print only a specific part of the JSON data "data": [{"y":"23","x": "12"}], but nothing appears on the HTML page.

Try out the Demo here: http://plnkr.co/edit/zy1C2z39dXuuHDx8eqxK?p=preview

Here is the JSON Data:

{"series": [{"meter": "instance", "data": [{"y": 1.0, "x": "2015-07-21T14:21:33"}, {"y": 1.0, "x": "2015-07-22T14:21:34"}, {"y": 1.0, "x": "2015-07-23T14:21:34"}, {"y": 1.0, "x": "2015-07-24T14:23:39"}, {"y": 1.0, "x": "2015-07-25T14:23:39"}, {"y": 1.0, "x": "2015-07-26T02:43:39"}, {"y": 1.0, "x": "2015-07-27T14:24:33"}], "name": "demo", "unit": "instance"}], "settings": {}}

Using AngularJS

 app.controller('ceilometerCtrl', function($scope, $http) {
 $http.get("http://192.168.206.133:8080/admin/metering")
      .success(function(response) {                    
         $scope.metrics=response.series[0].data;              
       });
 });

HTML Structure

<div ng-controller="ceilometerCtrl">
    <div ng-repeat="metric in metrics">
        Metric: {{metric.x}}
    </div>
</div>

The Result: nothing is displayed on the page

Metric:
Metric:
Metric:
Metric:
Metric:
Metric:
Metric:

Answer №1

To improve your code, there are two key changes that need to be made.

  1. Since series is an array, make the following adjustment:

    $scope.metrics=response.series.data;
    

The correct update is:

$scope.metrics=response.series[0].data;    
  1. The properties x and y correspond to the metric object. Update from:

     Metric: {{metric.data.x}}
    

The revised format should be:

 Metric: {{metric.x}}

Answer №2

Attempt

    <div ng-repeat="metric in metrics">
      Metric A:  {{metric.a}}
      Metric B:  {{metric.b}}
   </div>

Furthermore, in the controller, make a change to this line:

$scope.metrics=response.series.data;  

Update it to:

$scope.metrics=response.series[0].data;

Your Json is correct. The issue was with how you used ng-repeat. The modified code snippet should resolve your problem.

Answer №3

To display your data in a controlled manner, utilize the AngularJS filter named json:

{{ your.data | json }}

Answer №4

If you look at the code provided above:

$scope.metrics=response.series.data; 

You will notice that your $scope.metrics will return undefined because response.series is an array, not a JSON object.

There are two possible solutions to this issue

Approach 1:

app.controller('ceilometerCtrl', function($scope, $http) {

  $http.get("http://192.168.206.133:8080/admin/metering")
    .success(function(response) {
      /**
       * The response now looks like this:
       * {"series": [{"meter": "instance", "data": [{"y": 1.0, "x": "2015-07-21T14:21:33"}, {"y": 1.0, "x": "2015-07-22T14:21:34"},...}], "name": "demo", "unit": "instance"}]
       * By using response.series, you get an array of objects
       * To access each item's data property, you need to iterate over series and then over data within each item.
       * <div ng-repeat="s in series">
       *   <div ng-repeat="d in s.data">
       *     {{ d.x }} <br />
       *     {{ d.y }}
       *   </div>
       * </div>
       */
      $scope.series = response.series;
    });
});

If you prefer copy-pasting, here is the corresponding HTML

<div ng-repeat="s in series">
  <div ng-repeat="d in s.data">
    {{ d.x }} <br />
    {{ d.y }}
  </div>
</div>

Approach 2:

Retrieve the first element from your response

app.controller('ceilometerCtrl', function($scope, $http) {
  $http.get("http://192.168.206.133:8080/admin/metering")
    .success(function(response) {
      /**
       * By selecting the first element from the response array, you get a JSON object
       * { "meter": "instance","data": [{  "y": 1.0,  "x": "2015-07-21T14:21:33"}, ...],"name": "demo","unit": "instance" }
       * Simply iterate over the data series
       * <div ng-repeat="d in matrics.data">
       *     {{ d.x }} <br />
       *     {{ d.y }}
       * </div>
       */
      $scope.matrics = response.series[0];
    });
});

For the second approach, the HTML would be:

<div ng-repeat="d in matrics.data">
  {{ d.x }} <br />
  {{ d.y }}
</div>

I hope this information helps you tackle the problem effectively.

Answer №5

To simplify the process, you can utilize the "json" filter based on your data structure. In this case, accessing response.series[0].data; as mentioned earlier may be necessary. Once you have extracted the desired data, it becomes straightforward:

Metric: <pre>{{metrics.series[0].data|json}}</pre>

View a basic example here: http://jsfiddle.net/hLf1rLxz/


Following your request for an update, I noticed issues with your plunkr setup. The absence of the d3.time reference and errors related to RickSha were addressed by rearranging the code structure. By placing $scope.series above the initialization of new RickShaw, the displayed information was successfully corrected.

Updated plunker version: http://plnkr.co/edit/iMB4ElKqfAlM0wdyqpA7?p=preview

Necessary code adjustments:

<body ng-controller="MainCtrl">
   <pre>{{metrics | json}}</pre>

   <div id="chart"></div>
 </body>

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

If the request body exists, it should return a 409 error code

*Can anyone please help me with avoiding duplicate requests for existing names in NodeJS Express?* Here is my code: /* Post new person to persons */ app.post("/api/persons/", (req, res) => { const schema = { name: Joi.string().alphanum ...

The AngularJS directive that wraps the Kendo UI grid is unable to handle the kendoEvent properly

Our goal is to develop a displayBasket directive that will wrap kendoGrid and additional functionality. However, we are facing an issue where the gridDataBound function is not receiving kendoEvent. How can we resolve this problem? Here is an example in HT ...

My build process with gulp is not generating the expected output file. What could have gone awry?

Can anyone help me figure out why my gulp task is not generating any files? Below is the code for my task: import gulp from 'gulp'; import babelify from 'babelify'; import sourcemaps from 'gulp-sourcemaps'; import browserify ...

Guide on converting a JavaScript object into an array consisting of key and value pairs

I have information that appears as follows: [{"letter": "a", "word" : "apple"}, {"letter": "b", "word":"ball"}, {"letter": "a", "word":"alpha"}, {"letter": "c", "word":"cat"}] My goal is to convert it into: {"a":["apple", "alpha"], "b": ["ball"], "c":[" ...

What causes a statically generated page to appear without any style when transmitted to the client?

After setting up the Next.js official boilerplate with npx create-next-app and opening it in the browser, I observed that the static HTML document lacks styling: https://i.stack.imgur.com/mna6K.png I am concerned about potential FOUC issues. How can I en ...

Verify if the username or phone number is already in use (front end)

Is there a way to verify user or phone existence on the front-end form? I'm using Yup + Formik for all my requirements, and in my backend with Sequelize, I can check if a username or phone number already exists. passport.use( 'register&apos ...

How can I hide selected options in GraphQL playground?

I'm facing an issue in the playground with my view. When I try to add another option to select, pressing CTRL + space shows me every possible option, including the ones already selected. Is there a way to prevent this behavior? I only want to see the ...

Changing the size of circles in text and adjusting the dimensions of SVG elements

As a novice JavaScript programmer, I am attempting to resize circles and SVG elements based on the window size. Currently, my code creates circles of varying sizes, but I haven't been able to adjust them in relation to text size. var width = 600; va ...

extract the information from the JSON structure

Currently, I am in the process of learning JSON. $.ajax({ async: true, type: "POST", url: "fetch.....data.jsp", data: "vendorId="+vendor, success: function(json){ alert( "Received Data: " + ...

Angular2: Unable to find json property on object type

I am a beginner and struggling to solve this problem. I have tried to understand the errors but it's still not making sense to me. Whenever I use .map or .subscribe on the service, I get an error saying Property 'json' does not exist on typ ...

"Troubleshooting issue with Java Jersey not properly processing JSON parameters in Jax-

I've recently taken over a sizable project that involves numerous web services built using Jersey Jax-WS. One of my current tasks is to modify one of these services to accept JSON as a POST request. However, I'm encountering issues with receiving ...

JavaScript MIDI File player allows for the seamless playback of MIDI

Is there an easy way to play midi files in my browser? I came across this site: , but it seems a bit complex for me. I'm looking for something simpler like this: <div id="midi-player"></div> script $('#midi-player').midiplaye ...

Having trouble with AngularJS ng-repeat not functioning properly within inner properties?

Below is an object that I want to utilize with ng-repeat, but it doesn't seem to recognize the inner firstlang property: $scope.education{ institute : "example college", department :{ firstlang : "French" } } Here is how I am using ng-re ...

Stop execution of asynchronous functions in React useEffect when dependent variables change

Picture a scenario where I have a user interface with two controls: a date picker (linked to a state date) and a dropdown (linked to a state filter) In my React application, I am utilizing the useEffect hook to make an API call using both the date and fil ...

Guidelines for incorporating role-based permissions in a React application

I am developing a MERN application that has various features catering to different roles. I need the ability to display specific data, navigation options, and divs based on the user's role while hiding these elements from others. It is important to no ...

Extracting JSON from cURL response

After receiving a JSON output, I am looking to format it based on the description and subnet fields. { "code": 200, "success": true, "data": [{ "id": "66", "subnet": "0.0.0.0", "mask": "", "sectionId": "1", "description ...

Maintain the state of various panels on page load with the Bootstrap Accordion feature

I have implemented a Bootstrap accordion on my form page which allows users to open multiple panels simultaneously. Upon submitting the form, I want to preserve the state of any open Bootstrap accordion panels. To achieve this, I utilized code from stack ...

JQuery's document.ready function triggers prematurely on dynamically loaded HTML content

When loading dynamic content, I use the following method: $('#my-div').load('my.html'); The code inside my.html looks like this: <html> <head> </head> <body> <script> $(fu ...

Adjusting the text of a button when hovering over it will also trigger a resizing of the

Currently, I am facing an issue where the bootstrap button's size changes when hovered over. My intention is to have the bootstrap button remain a fixed size while only the text inside it changes using javascript for mouseover and mouseout events. How ...

Guide to setting up a Node, Express, Connect-Auth, and Backbone application architecture for server-side development

As someone who primarily works on the client-side, I have recently ventured into the realm of server-side JavaScript. My initial plan for my first Node.js application involves a server-side setup that primarily serves an empty shell along with a plethora o ...