I'm currently working on setting up a basic RESTful API with Django Rest Framework and integrating it with AngularJS. Despite following various tutorials and learning about controllers and resources in Angular, I seem to be facing an issue in accessing JSON data correctly within my template.
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**** I added the filter here to test, and it does do the filtering as intended, but still no text shows up in the <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>
The output of a GET request on /api/posts/ is shown below:
[
{
"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/"
},
...
]
Even though the correct number of boxes are displayed for each post object, the template only renders blank grey boxes without any title or content. What could be causing this issue?
EDIT: There are no errors shown in the console, and the GET request returns a status code of 200 along with application/json response. When I log $scope.posts, it displays
[Resource, Resource, Resource, Resource, Resource, Resource, Resource, $promise: Object, $resolved: true]
. Additionally,
for (key in $scope.posts){
console.log(posts[key]);
}
prints
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"…}