我正在尝试学习
angularjs,并尝试将数据绑定到从Rest API返回的数组中.我有一个简单的azure api返回人物对象的数组.服务网址是
http://testv1.cloudapp.net/test.svc/persons.
我的控制器代码看起来像:
angular.module("TodoApp",["ngResource"]);
function TodoCtrl($scope,$resource) {
$scope.svc = $resource('http://testv1.cloudapp.net/test.svc/persons',{
callback: 'JSON_CALLBACK'
},{
get: {
method: 'JSONP',isArray: true
}
});
$scope.items = $scope.svc.get();
$scope.msg = "Hello World";
}
我的html看起来像:
<html>
<head></head>
<body>
<div ng-app="TodoApp">
<div ng-controller="TodoCtrl">
<h1>{{msg}}</h1>
<table class="table table-striped table-condensed table-hover">
<thead>
<th>Email</th>
<th>First Name</th>
<th>Last Name</th>
</thead>
<tbody>
<tr ng-repeat="item in items">
<td>{{item.Email}}</td>
<td>{{item.FirstName}}</td>
<td>{{item.LastName}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</body>
</html>
问题:上面的表格没有显示任何数据.我可以在Firebug中看到api的呼叫,也可以看到api的JSON响应.我正在做的错误是导致REST api的数据绑定不起作用?
PS:JSfiddle演示这个问题是:http://jsfiddle.net/jbliss1234/FBLFK/4/
为了处理带有$资源服务的数组,建议您使用查询方法.如下所示,构建查询方法来处理数组.
{ 'get': {method:'GET'},'save': {method:'POST'},'query': {method:'GET',isArray:true},'remove': {method:'DELETE'},'delete': {method:'DELETE'} };
您应该使用的代码为了将此数组返回到您的作用域
angular.module("TodoApp",["ngResource"]);
function TodoCtrl($scope,$resource) {
var svc = $resource('http://testv1.cloudapp.net/test.svc/persons');
$scope.items = svc.query();
$scope.msg = "Hello World";
}
这假设您的REST API正在运行,并将返回一个数组.
进一步阅读文档
http://docs.angularjs.org/api/ngResource.$resource