javascript - ng-repeat 仅显示最后一项

标签 javascript angularjs lodash

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

我收到一个包含 WordPress 帖子的 JSON 对象,但是当我尝试在 DOM 中渲染这些帖子时,列表中出现 12 次的唯一帖子是最后一项

<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();

服务

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

最佳答案

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

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

尝试:

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

关于javascript - ng-repeat 仅显示最后一项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30182773/

相关文章:

javascript - 如何在 JavaScript 中有条件合并列表中的某些元素?

javascript - Node.js 支持 =>(箭头函数)

javascript - Gulp 编译错误 js.72。未处理的错误

javascript - 不同的 JavaScript block 类型

javascript - 使用 AngularJs 显示图像预览并上传文件

javascript - 在 $http 加载的内容上渲染 AngularJS 指令

javascript - $http.post 文件大小限制?当然看起来像它

javascript - 如何从包含 div 的 textarea 中获取值

javascript - Lodash - 从对象中删除嵌套属性

javascript - 为什么 jQuery.extend() 比 Lodash .clone() 更快