The problem I'm having is that when using the below custom filter to order by date, I also get '$promise' rendered in the view with empty list items. I'm very new to angular and don't know too much about promises so bear with me.
This is an example of the JSON response from the server:
{"September 21st":[{"id":6,"title":"Test 2","url":"www.google.com","tagline":"Test tagline 2","created_at":"2014-09-21T00:00:00.000Z","updated_at":"2014-09-20T20:37:47.317Z","vote_count":9}],"September 20th":[{"id":7,"title":"Test 3","url":"www.google.com","tagline":"Test Tagline 2","created_at":"2014-09-20T21:16:05.676Z","updated_at":"2014-09-20T21:16:05.676Z","vote_count":2},{"id":5,"title":"Test 1","url":"www.google.com","tagline":"Test tagline 1","created_at":"2014-09-20T19:30:44.672Z","updated_at":"2014-09-20T21:25:33.093Z","vote_count":20}]}
I have a Post resource:
.factory('Post', ['$resource', function($resource) {
var Post = $resource('http://localhost:3000/api/posts/:id.json', {id: '@id'}, {
update: {
method: 'PUT'
}
});
return Post;
}]);
And I'm accessing it in my controller using:
$scope.postList = Post.get();
This is my html:
<section ng-controller='MainController'>
<ul ng-repeat="posts in postList | orderObjectBy:'created_at':false">
<h1>{{ posts.__originalKey }}</h1>
<li ng-repeat='post in posts'>
<p>{{ post.vote_count }}</p>
<button ng-click='upvote(post)' ng-disabled='!currentUser || hasVoted(post.id)'></button>
<a href="{{ post.url }}">{{ post.title }}</a>
</li>
</ul>
</section>
And here is the orderObjectBy filter:
.filter('orderObjectBy', function() {
return function(items, field, reverse) {
var filtered = [];
angular.forEach(items, function(item, key) {
item.__originalKey=key;
filtered.push(item);
});
filtered.sort(function (a, b) {
return (a[field] > b[field] ? 1 : -1);
});
if(reverse) filtered.reverse();
return filtered;
};
});
If I remove the filter, the view renders as expected but as soon as I use the filter I get '$promise' as a heading with the empty list items and I haven't been able to figure out why. Thanks for your help!
Post
is resource or custom factory? – dfsq Sep 21 '14 at 14:55