2015-05-12 111 views
0

我知道這可能是我的錯。ng-repeat只顯示最後一項

我接受了其中包含的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; 
     }); 
     }) 
    } 
}); 
+0

它不應該是'post.title'&'post.date',而不是'posts.title'&'posts.date' –

+0

@PatrickEvans如果我這樣做,我可以在DOM中看不到任何東西 – NietzscheProgrammer

回答

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; 
    }) 
} 
+0

你是對的,謝謝。 – NietzscheProgrammer

1

您應該使用服務裏面ng-repeatpost將成爲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

+0

我只是修復它,對不起,反正如果我改變它的方式,我不能看到任何東西在DOM – NietzscheProgrammer