Freya Freya - 5 months ago 11
JSON Question

Response not displayed in the view (nodejs, mysql, angularjs)

I am trying to populate a basic angular app with data from a database. Example similar to that in w3schools. This is the code so far:

<div ng-app="myApp" ng-controller="customersCtrl">

<table>
<tr ng-repeat="x in names">
<td>{{ x.id }}</td>
<td>{{ x.appid }}</td>
</tr>
</table>
</div>

<script>
var app = angular.module('myApp', []);
app.controller('customersCtrl', function($scope, $http) {
$http.get("http://localhost:3000/test")
.then(function (response) {$scope.names = response.data.records;});
});
</script>


However, no data are retrieved. The response i get from http://localhost:3000/test is the following:


[

{"id":1,"appid":1},{"id":2,"appid":1},{"id":7,"appid":1},
{"id":20,"appid":1},{"id":38,"appid":1},{"id":39,"appid":1},{"id":40,"appid":1},{"id":41,"appid":3},{"id":44,"appid":3},{"id":70,"appid":2},{"id":71,"appid":2},{"id":72,"appid":2}

]


I checked it both from the browser and from postman. If I replace response.data.records with the response above, the table displays the values in the response.

I know I must be messing something up, but somehow I am missing it. My best guess would be that of the format of the response.

Answer

You need to remove .records from the respnse.data

$http.get("http://localhost:3000/test")
        .then(function (response) {$scope.names = response.data;}); 

Since you are directly receiving an array just assign array from response directly to $scope.names.