我是 Angular 的新手,我正在做一些原型(prototype)设计。不幸的是,当我调用 REST 服务时,我在显示数据时遇到了问题。控制台未提供任何线索,因为没有错误返回。
HTML 如下:
<!doctype html>
<html ng-app="statViewer">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Test Angular Page</title>
<script src="js/angular.min.js" type="text/javascript"></script>
<script src="js/statViewer.js" type="text/javascript"></script>
</head>
<body ng-controller="MainController">
<h1> {{title}} </h1>
<table>
<thead>
<tr>
<th>Name</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="stat in stats">
<td>{{stat.MessageName}}</td>
<td>{{stat.TypeCount}}</td>
</tr>
</tbody>
</table>
</body>
</html>
JS如下:
(function() {
var app = angular.module("statViewer", []);
var MainController = function($scope, $http) {
$scope.title = "Angular test page";
$http.get("http://localhost:8080/API/getstats.json")
.then(onStatsComplete);
var onStatsComplete = function(response)
{
$scope.stats = response.data;
};
};
app.controller("MainController", MainController);
}());
我看到该服务正在被调用,因为在控制台窗口中它打印出调用已被触发。调用 REST API 的结果如下:
[
{
"TypeCount": 45,
"SentDate": "2014-08-20T00:00:00.000Z",
"MessageName": "Message Type 1"
}
]
最佳答案
在调用 $http.get
之后,您正在使用回调函数定义变量 onStatsComplete
。。因此,在您调用 $http.get
时,值 undefined
被传递给 then 而不是您的回调函数。像这样交换行:
var onStatsComplete = function(response)
{
$scope.stats = response.data;
};
$http.get("http://localhost:8080/API/getstats.json")
.then(onStatsComplete);
另见 this question关于编写 var y = function(){...}
和 function y(){...}
的区别。
关于javascript - Angular.js 和显示 Rest JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25408689/