【问题标题】:ng-repeat displaying only the last itemng-repeat 只显示最后一项
【发布时间】:2015-05-12 05:51:03
【问题描述】:

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

我收到一个包含 WordPress 帖子的 JSON 对象,但是当我尝试在 DOM 中呈现这些帖子时,列表中唯一出现 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;
        });
      })
    }
});

【问题讨论】:

  • 应该是post.title & post.date 而不是posts.title & posts.date
  • @PatrickEvans 如果我这样做,我在 DOM 中看不到任何东西

标签: javascript angularjs lodash


【解决方案1】:
_.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;
  })
}

【讨论】:

    【解决方案2】:

    您应该在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

    【讨论】:

    • 我只是修复它,对不起,无论如何如果我这样改变它,我在 DOM 中看不到任何东西
    猜你喜欢
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多