我是Angularjs的新手。我正在创建一些员工应用程序,它基本上从http call(json)
获取数据并使用angularjs显示它。
问题是在从http
调用响应之前我的视图已执行,因此我的输出页面中没有显示任何内容。我知道应该有一些逻辑来处理异步调用,但我不知道,所以有人可以帮助我吗?
Home.html中
<html ng-app="employeeApp">
<head>
<link rel="stylesheet"
href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<meta charset="utf-8">
<title>Employee Example</title>
<script
src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.2.1/angular.min.js"></script>
<script>
var employeeApp = angular.module('employeeApp', []);
employeeApp.controller('EmployeeCtrl', ['$http','$scope',
function(http, scope) {
http.get('http://localhost:9999/employee/7').success(
function(data) {
scope.employees = data;
});
} ]);
</script>
</head>
<body ng-controller="EmployeeCtrl">
<table class="table table-striped">
<tr>
<th>ID</th>
<th>NAME</th>
<th>AGE</th>
<th>LOCATION</th>
</tr>
<tr ng-repeat="employee in employees">
<td>{{employee.id}}</td>
<td>{{employee.name}}</td>
<td>{{employee.age}}</td>
<td>{{employee.location}}</td>
</tr>
</table>
<hr>
<hr>
</body>
</html>
实际输出:
我的预期输出
注意:
如果我从json文件加载或从Web浏览器运行我得到了预期的输出,但它没有在Angular脚本中工作。
http://localhost:9999/employee/7
{"id":7,"age":65,"name":"test","location":"singapore"}
答案 0 :(得分:4)
您没有看到任何数据,因为'employees'不是数组(即您的端点只返回一个对象)。
从您的端点返回对象数组,或者如果您始终只获得一个对象,则删除ng-repeat并将“employee”替换为绑定中的“employees”。
注意:在ng-repeat中使用object时,它将迭代对象中的属性。
答案 1 :(得分:3)
您希望ng-repeat能够获得对象的“列表”。你得到的是一个单一的对象,ng-repeat可能会迭代。但是,每个属性都没有id,name等的预期属性。
你应该在你的ajax响应中返回的内容应该更像这样:
[
{"id":7,"age":65,"name":"test","location":"singapore"},
{"id":7,"age":65,"name":"test","location":"singapore"},
{"id":7,"age":65,"name":"test","location":"singapore"},
{"id":7,"age":65,"name":"test","location":"singapore"}
]
或者,对于单个项目,它将是:
[
{"id":7,"age":65,"name":"test","location":"singapore"}
]
答案 2 :(得分:1)
您可以使用Chrome开发者工具(在Chrome上按F12)来调试脚本。 观看&#34;网络&#34;来自服务器的响应数据的选项卡。
我通常用来检查这样的bug的另一种方法是将varaiable直接打印到模板上,如下所示:
<body ng-controller="EmployeeCtrl">
{{employees}}
</body>
有时这可以帮助我找出对我的数据感兴趣的内容。在解决问题后,请记住清除:)