2017-02-15 128 views
0

我正在嘗試使用角度ng-repeat指令迭代嵌套的json對象中的註釋,但在某種程度上它似乎無法訪問它,我做錯了什麼?ng-repeat嵌套的json數組angularJS

這裏JSON

 posts: [ 
     { 
      title: 'Free pizza at club meetings', 
      upvotes: 15, 
      comments: [ 
       {commento:'comment1'}, 
       {commento:'comment2'} 
      ] 
     }, 
     { 
      title: 'End all club emails with Laffy Taffy jokes', 
      upvotes: 9, 
      comments: [], 
     } 
]; 

,這裏的景色

的視圖給我錯誤

+1

'NG-重複=' – Laazo

+0

對不起@Azola 「在post.comments評論:」 我沒有看到張貼我的答案之前,您的評論。如果你發佈一個答案,我會刪除我的,所以你得到代表。 –

+0

不用擔心@BernhardHofmann – Laazo

回答

0

只是小的語法錯誤 - 檢查下面的代碼:JSFiddle

var app = angular.module("demoApp", []); 
 

 
app.controller('myCtrl', function($scope){ 
 

 
    $scope.posts= [ 
 
      { 
 
       title: 'Free pizza at club meetings', 
 
       upvotes: 15, 
 
       comments: [ 
 
        {commento:'comment1'}, 
 
        {commento:'comment2'} 
 
       ] 
 
      }, 
 
      { 
 
       title: 'End all club emails with Laffy Taffy jokes', 
 
       upvotes: 9, 
 
       comments: [{commento:'comment3'}, 
 
        {commento:'comment4'}] 
 
      } 
 
    ]; 
 
\t \t $scope.upVote = function(post){} 
 
});
<div ng-app="demoApp" ng-controller="myCtrl"> 
 
<div ng-repeat="post in posts"> 
 
    <span>{{post.title}}</span> 
 
    <p class="glyphicon glyphicon-plus-sign" ng-click="upVote(post)" style="cursor:pointer;"></p> Upvotes: {{post.upvotes}} 
 
    
 
    <p ng-repeat = "comment in post.comments"> 
 
     {{comment.commento}} 
 
    </p> 
 
</div> 
 
</div>

1

你的NG-重複的語法是錯誤的:

<p ng-repeat comment in post.comments> 

應該

<p ng-repeat="comment in post.comments"> 
0

確定只是一個格式錯誤

<p ng-repeat="comment in post.comments"> 
+0

請標記爲您解決問題的答案(勾號),以便問題不會「未答覆」。沒有回答的問題有時會讓人們花時間看看(已經回答的)問題,他們可以幫助別人。 –

0

觀察:

  • 使用<p ng-repeat="comment in post.comments">代替<p ng-repeat comment in post.comments>
  • $scope.posts對象未被正確聲明。使用$scope.posts = []而不是$scope.posts: []

DEMO

var myApp = angular.module('myApp',[]); 
 

 
myApp.controller('MyCtrl',function($scope) { 
 
    $scope.posts = [ 
 
     { 
 
      title: 'Free pizza at club meetings', 
 
      upvotes: 15, 
 
      comments: [ 
 
       {commento:'comment1'}, 
 
       {commento:'comment2'} 
 
      ] 
 
     }, 
 
     { 
 
      title: 'End all club emails with Laffy Taffy jokes', 
 
      upvotes: 9, 
 
      comments: [], 
 
     } 
 
]; 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
<div ng-app="myApp" ng-controller="MyCtrl"> 
 
<div class="col-lg-12 col-xs-12 comment" ng-repeat="post in posts | orderBy:'-upvotes'"> 
 
    <p>{{post.title}}</p> 
 
    <p> 
 
     <span class="glyphicon glyphicon-plus-sign" ng-click="upVote(post)" style="cursor:pointer;"></span> Upvotes: {{post.upvotes}} 
 
    </p> 
 
    <p ng-repeat="comment in post.comments"> 
 
    {{comment.commento}} 
 
    </p> 
 
</div> 
 
</div>