user3121518 user3121518 - 1 month ago 6
AngularJS Question

AngularJS - http get response (JSON Array) and display in html

I've created a servlet in Java that displays an array using;

printWriter.println(jsonarray);


And the array shows up on the servlet page, but that's where the fun stops. I want to display the array as a table on a webpage using AngularJS, which I have no prior experience with. But I can't get the array to show on the webpage let alone display it as a table

HTML

<div ng-app="myApp" ng-controller="myController">{{myArray}}</div>


AngularJS

var app = angular.module("myApp", []);

app.controller("myController", function($scope, $http)
{
$scope.recipes = null;
$scope.message = null;
$scope.filterString = '';
$scope.sortByName = false;
$scope.sortOrder = '';
$scope.setSortOrder = function()
{
if($scope.sortByName)
{
$scope.sortOrder = 'name';
}
else
{
$scope.sortOrder = '';
}
}


var connection = $http(
{
method: 'GET',
url: 'http://localhost:8080/students'
})


.then(function(response)
{
$scope.myArray = response.data;
})
.catch(function(response)
{
// It is OK not to take any action here because it would be
// clear to the user if the list operation is succesfull or not
})

.finally(function(config) // induce a syntax error here and see what happens
{
// It is OK not to take any action here because it would be
// clear to the user if the list operation is succesfull or not
});


});
//end controller


Ok, fixed some minor errors but now I'm getting a 404 file not found error

http://localhost:8080/students


When I visit the link in my browser I get the array displayed but the webpage is giving me;

404 Error Image

Changing the angular.js version fixed the 404, I had the min version 1.4.8 before

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>

Answer

Try:

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

  <table>
    <tr ng-repeat="x in myArray">
      <td>{{ x.name }}</td>
      <td>{{ x.age }}</td>
    </tr>
  </table>

</div>
Comments