Read JSON and print to html with Angularjs

Asked

Viewed 2,757 times

2

I am trying to print the data of a JSON file in html using Angularjs, running everything through XAMPP and in my htdocs/test folder there are 3 files (index.html, main.js, test.json). The console shows no errors, I even tried debugging by firefox, I put a breakpoint in $http.get, but it never gets there. Follow the JS code:

var app = angular.module('myApp', []);
app.controller("myCtrl", function ($http, $scope) {
    $http.get('teste.json').then(function (response) {
        $scope.myData = response;
    });
});

JSON:

[{"id":"1","name":"John"},
 {"id":"2","name":"Paul"}] </br/>

HTML:

<ul>
    <li ng-repeat="data in myData">
        {{data.id}}
        {{data.name}}
    </li>
</ul>
  • In the network tab in Developer tools http is run?

  • Gets status 200, so I guess Sergio

  • I don’t know much about angular, but as far as I know, you need to define the services that make the ajax requests and you can send them to the controller with $Scope’s

  • @clr19 can see the answer of this 200 also?

  • Interesting is getting status 200 but is not stopping at breakpoint

  • I couldn’t see the answer to the 200, but I really find it strange not to stop at the breakpoint, I can’t imagine what the problem would be.

  • If this is your complete HTML, it won’t work because at no point do you declare the beginning of the Angular application (with ng-app.)

Show 2 more comments

1 answer

1

The response of the request, injected into the variable sponse, does not contain the list of values you expect. According to the documentation available in https://docs.angularjs.org/api/ng/service/$http:

The Response Object has These properties:

  • data - {string|Object} - The Response body Transformed with the Transform functions.
  • status - {number} - HTTP status code of the Response.
  • headers - {Function([headerName])} - Header getter Function.
  • config - {Object} - The Configuration Object that was used to generate the request.
  • statusText - {string} - HTTP status text of the Response.

Therefore, I believe that your controller it should be like this:

app.controller("myCtrl", function ($http, $scope) {
    $http.get('teste.json').then(function (response) {
        $scope.myData = response.data;
    });
});

If you prefer, use console log. to verify the answer:

console.log(response);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.