【发布时间】:2014-10-28 18:59:38
【问题描述】:
我使用 Django Rest Framework 设置了一个简单的 RESTful API,我正在尝试使用 AngularJS 来使用它。我已经阅读了有关角度控制器和资源的信息,并且正在学习多个教程,但由于某种原因,在我的模板中,我似乎无法正确访问 JSON。
app.js
var blogApp = angular.module('blogApp', ['ngResource']);
blogApp.factory('Post', ['$resource', function($resource) {
return $resource('/api/posts/:slug/', { slug:'@slug'});
}]);
blogApp.controller('postController', ['$scope', 'Post', function($scope, Post) {
$scope.posts = []
Post.query().$promise.then(function(posts) {
$scope.posts = posts;
for (key in posts){
console.log(posts[key]);
}
});
}]);
index.html
****EDIT**** 我在此处添加了过滤器进行测试,它确实按预期进行了过滤,但<div>'s 中仍然没有文本显示
<div class="container">
<div class="col-sm-10">
<div ng-controller="postController">
<input type="text" ng-model="textTest">
<div class="well" ng-repeat="(key, post) in posts | filter: textTest">
<h1>{{ post.title }}</h1>
{{ post.content }}
</div>
</div>
</div>
</div>
这是我在 /api/posts/ 上执行 GET 时返回的内容
[
{
"url": "http://localhost:8000/api/posts/i-had-a-api-his-name-was-bingo/",
"id": 0,
"title": "I had a api... his name was Bingo",
"content": "E-I-E-I-O",
"owner": "Heather",
"comments": "http://localhost:8000/api/posts/i-had-a-api-his-name-was-bingo/comments/"
},
{
"url": "http://localhost:8000/api/posts/if-i-could-show-you-the-world/",
"id": 1,
"title": "If I Could Show You The World",
"content": "It would be shining, and shimmering",
"owner": "Heather",
"comments": "http://localhost:8000/api/posts/if-i-could-show-you-the-world/comments/"
},
...
]
在模板中,所有显示的是一个空白的灰色框(由于引导类),没有帖子的标题或内容,但正确数量的框确实显示了帖子对象的数量。我错过了什么?
编辑:控制台没有显示错误,GET 请求返回 200 application/json。我有一个 console.log($scope.posts) 正在打印出[Resource, Resource, Resource, Resource, Resource, Resource, Resource, $promise: Object, $resolved: true]。还有,
for (key in $scope.posts){
console.log(posts[key]);
}
打印出来
Resource {url: "http://localhost:8000/api/posts/i-had-a-api-his-name-was-bingo/", id: 0, title: "I had a api... his name was Bingo", content: "E-I-E-I-O", owner: "Heather"…}
【问题讨论】:
-
您在控制台中看到了什么?使用 DevTools->Network->filter XHR 看看返回什么
标签: javascript angularjs rest django-rest-framework