Read JSON and print in html with angularJS

2

I am trying to print the data from a JSON file in html using AngularJS, running everything by XAMPP and in my htdocs / test folder has 3 files (index.html, main.js, test.json). The console does not show any errors, I even tried to debug by firefox, I put a breakpoint in $ http.get, but it never gets to that point. Follow the code JS:

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>
    
asked by anonymous 21.05.2016 / 14:22

1 answer

1

The request response, injected into the response variable, does not contain the list of values you expect. According to the documentation available at link $ 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.
  •   

So, I think your controller should look 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 check the answer:

console.log(response);
    
27.07.2016 / 20:21