ng-repeat 只显示最后一项

ng-repeat displaying only the last item

我知道这可能是我的错误。

我收到一个包含 WordPress post 的 JSON 对象,但是当我尝试在 DOM 中呈现那些 post 时,唯一的 post在列表中出现了12次,是最后一项

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

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

</div>

控制器

$scope.posts = [];

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

服务

.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;
        });
      })
    }
});

您应该在 ng-repeat 中使用 postpost 将是 posts.

中的单个对象
<div ng-repeat="post in posts">

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

参考文档:https://docs.angularjs.org/api/ng/directive/ngRepeat

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

这就是错误所在。 Lodash 循环遍历 posts 并每次将 $scope.posts 分配给一个 post,这就是为什么你得到最后一个。

尝试:

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