Non
Non

Reputation: 8589

ng-repeat displaying only the last item

I know this is probably my mistake.

I am receiving a JSON object which contains WordPress posts, but when I try to render those posts in the DOM, the only post which is 12 times in the list, is the last item

<div ng-repeat="post in posts">

    <h2 ng-bind-html="post.title"></h2>
    <p>{{:: post.date | date}}</p>

</div>

controller

$scope.posts = [];

$scope.doRefresh = function() {
  $scope.posts = FreshlyPressed.getBlogs($scope);
  $scope.$broadcast('scroll.refreshComplete');
}
$scope.doRefresh();

the service

.service('FreshlyPressed', function($http, $q) {
 return {

getBlogs: function($scope) {
  var posts = [];
  $http.get('http://urbanetradio.com/wp-json/posts')
    .success(function(result) {
      _.each(result, function(posts) {
          console.log(posts.title);
          $scope.posts = posts;
        });
      })
    }
});

Upvotes: 0

Views: 141

Answers (2)

jfornoff
jfornoff

Reputation: 1378

_.each(result, function(posts) {
   console.log(posts.title);
   $scope.posts = posts;
});

This is where the mistake is. Lodash loops through the posts and and assigns $scope.posts to ONE post each time, thats why you get the last one.

Try:

$http.get('http://urbanetradio.com/wp-json/posts')
.success(function(result) {
    $scope.posts = result;
  })
}

Upvotes: 1

Tushar
Tushar

Reputation: 87233

You should be using post inside ng-repeat. post will be the individual object inside posts.

<div ng-repeat="post in posts">

    <h2 ng-bind-html="post.title"></h2>
    <!--              ^^^^          -->
    <p>{{:: post.date | date}}</p>
    <!--    ^^^^               -->
</div>

Reference Docs: https://docs.angularjs.org/api/ng/directive/ngRepeat

Upvotes: 1

Related Questions