I have a simple RESTful API set up using Django Rest Framework and I'm trying to use AngularJS to consume it. I've read about controllers and resources in angular and I'm following multiple tutorials, but for some reason in my template I can't seem to access the JSON properly.
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>
This is what is returned if I do a GET on /api/posts/
[
{
"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/"
},
...
]
In the template, all that shows up is a blank grey box (because of the bootstrap class) with no title or content from the posts, but the proper number of boxes do show up for the number of post objects. What am I missing?
EDIT: the console shows no errors, and the GET request is returning 200 application/json. I have a console.log($scope.posts) which is printing out [Resource, Resource, Resource, Resource, Resource, Resource, Resource, $promise: Object, $resolved: true]
. Also,
for (key in $scope.posts){
console.log(posts[key]);
}
prints out
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"…}