Kevin Kai Kevin Kai - 5 months ago 17
AngularJS Question

Consume Rest web service with AngularJS

This is my json data from my web service

[{"cameraid":"ggh","timestamp":"2016/05/10 01:31","filename":"ffffpg"},
{"cameraid":"mason","timestamp":"2016/05/10 05:31","filename":"aaa.png"}


My html file

<!doctype html>
<html ng-app="camListApp">
<head>
<title>hi AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script>
var camListApp = angular.module('camListApp');
camListApp.controller('Hello', ['$scope', '$http', function($scope, $http){
function Hello($scope, $http) {
$http.get('http://localhost/camera/list').
success(function(data) {
$scope.record= data;
});
}
</script>
</head>
<body>
<div ng-controller="Hello">
<table border = 1>
<thead>
<tr>
<th>camid</th>
<th>Timestamp</th>
<th>Filename</th>

</tr>
</thead>
<tbody>
<tr ng-repeat="record in record">
<td>{{record.cameraid}}</td>
<td>{{record.timestamp}}</td>
<td>{{record.filename}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>


no data on table

When I run my browser, no data is show in the table. What have I miss out or done wrong? Anybody can help? As i want to display all the data in the table

Answer

There are below issues in your code, which once fixed will make yor code working:

  1. Missing [] from module definition. Change it as below:

    var camListApp = angular.module('camListApp', []);
    
  2. The controller definition is incorrect as you have 2 callback functions (One within other). You only need one:

    camListApp.controller('Hello', ['$scope', '$http', function($scope, $http){
      $http.get('http://localhost/camera/list').
        success(function(data) {
            $scope.record= data;
        });
    }]);
    

Also the preferred way of handlin promises is using .then instead of .success

  1. When you use the $http service it wraps up your data in an object and actual data is an attribute exposed on the returned response in callback. Access the data attribute in response as below:

    $http.get('https://api.github.com/users/addi90/repos').then(function(response) {
      $scope.records= response.data;
    });
    

I have created a working bin with sample data from my github repos: https://jsbin.com/qejapayuhi/1/edit?html,js,console,output