Joh*_*iss 14 angularjs angularjs-ng-repeat
我正在尝试学习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";
}
Run Code Online (Sandbox Code Playgroud)
我的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>
Run Code Online (Sandbox Code Playgroud)
问题:上面的html表格没有显示任何数据.我可以在Firebug中看到对api的调用,也可以看到来自api的JSON响应.我做错了什么导致数据绑定到REST api不起作用?
PS:JSFiddle演示此问题的地址是:http://jsfiddle.net/jbliss1234/FBLFK/4/
Gwa*_*189 29
为了使用$ resource服务处理数组,建议您使用查询方法.如下所示,查询方法是为处理数组而构建的.
{ 'get': {method:'GET'},
'save': {method:'POST'},
'query': {method:'GET', isArray:true},
'remove': {method:'DELETE'},
'delete': {method:'DELETE'} };
Run Code Online (Sandbox Code Playgroud)
为了将此数组返回到您的范围,您应该使用的代码是
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";
}
Run Code Online (Sandbox Code Playgroud)
这假设您的REST API正在运行并将返回一个数组.
如需进一步阅读,请访问文档
http://docs.angularjs.org/api/ngResource.$resource
Bla*_*icz 10
只是想交叉发布我对Aleksander在另一个stackoverflow问题上给出的解决方案的改编:https://stackoverflow.com/a/16387288/626810:
methodName: {method:'GET', url: "/some/location/returning/array", transformResponse: function (data) {return {list: angular.fromJson(data)} }}
Run Code Online (Sandbox Code Playgroud)
所以当我调用这个函数时:
var tempData = ResourceName.methodName(function(){
console.log(tempData.list); // list will be the array in the expected format
});
Run Code Online (Sandbox Code Playgroud)
显然,如果您需要在多个方法/资源中使用GET数组,这有点笨重,但它似乎有效.
如果您有嵌套对象,请使用isArray参数:
angular.module('privilegeService', ['ngResource']).
factory('Privilege', function ($resource) {
return $resource('api/users/:userId/privileges',
{userId: '@id'},
{'query': {method:'GET', isArray:false}});
});
Run Code Online (Sandbox Code Playgroud)
您可以使用container.object.property符号来访问对象及其属性.
| 归档时间: |
|
| 查看次数: |
47382 次 |
| 最近记录: |