我正在尝试使用从我的控制器填充的列表呈现 html表。这就是我在做的事情:
//Home Controller
app.controller("HomeController", function ($scope, $location, ExamService, AuthenticationService, $cookieStore) {
$scope.items = '[{"id":"1","title":"Test 1","description":"this is a description"}]';
});
并在页面中:
<table class="table" ng-controller="HomeController">
<th>Id</th>
<th>Title</th>
<th>Description</th>
<tr ng-repeat="item in items">
<td>{{item.id}}</td>
<td>{{item.title}}</td>
<td>{{item.description}}</td>
</tr>
</table>
然而,这会生成一个包含109个tr节点的空白表...我做错了什么?请帮忙
答案 0 :(得分:5)
问题是$scope.items
是字符串文字。
相反,请使用数组文字:
$scope.items = [{"id":"1","title":"Test 1","description":"this is a description"}];
或更短:
$scope.items = [{id: 1,"title":"Test 1",description:"this is a description"}];
(fiddle)
为什么会出现这种混乱?
在我看来,这是因为人们常常混淆JSON - 数据交换格式(在JS中存储在字符串中)和JavaScript对象文字。 []
用于JS语言和JSON数据交换格式的数组对象文字。见What are the differences between JSON and JavaScript object?