2016-05-21 4 views
1

私は現在、Redditに似て、無限にネストされたコメント(およびその返信)を試みています。AngularJS [無限ダイジェストサイクル]の無限にネストされたコメントのレンダリングビュー

は、私は現在、一般的な形式の大規模な構造を持っている:すべてのコメントは、一般的なdiv templateに従うと、その返信がちょうどmargin-left:50px;追加されているので

[ 
    { 
     comment_id: 1 
     comment_text: "root1" 
     replies:[ 
      { 
       comment_id: 2 
       comment_text: "reply1", 
       replies: [ 
         .... 
       ] 
      } 
     ] 
    }, 
    { 
     comment_id: 3 
     comment_text: "root2" 
     replies:[ 
       ... 
     ] 
    }, 
] 

、私は再帰的ng-repeatを使用して、このチュートリアルに続き、再帰的にテンプレートが含まれていますそして、その回答

http://benfoster.io/blog/angularjs-recursive-templates

だから私のコードはHTMLでこのようなものです:

<script type="text/ng-template" id="commentTree"> 
    <div> 
     <img ng-src="{{comment.author.avatar}}" style="height:50px;"> 
     <a ng-href="/user/{{comment.author.user_id}}">{{comment.author.username}}</a> 
     <br/> 
     <small><strong>Posted</strong> <span am-time-ago="comment.date_posted"></span></small> 
     <p> 
      {{comment.comment_text}} 
     </p> 
     <span style="margin-right:5px;"> 
      <a href ng-click="comment.show_reply_box = true;" ng-show="!comment.show_reply_box"> 
      Reply 
      </a> 
      <div ng-show="comment.show_reply_box"> 
       <textarea ng-model="comment.possible_reply" class="form-control" rows="3" placeholder="Write your reply here..."></textarea> 
       <span style="margin-right:10px;"><button class="btn btn-default btn-sm" ng-click="vm.post_comment(comment, comment.possible_reply)">Comment</button></span> 
       <button class="btn btn-default btn-sm" ng-click="comment.show_reply_box = false;">Cancel</button> 
      </div> 
     </span> 
    </div> 
    <hr> 
    <div ng-repeat="comment in comment.replies" ng-include="'commentTree'" style="margin-left:50px;"> 
    </div> 
</script> 

    <div ng-repeat="comment in comment.replies" ng-include="'commentTree'" style="margin-left:50px;"> 
    </div> 

しかし、問題はng-repeatが極端にひどく最適化されていることであると私は私が午前ネストされたng-repeat Sによるinfdigエラーサイクルを取得しています。これは私が持っているコメントの数によって引き起こされているのではなく、むしろ私がng-repeatsを入れ子にしているという事実によると確信しているので、これは変です。ただし、非常に有益なデータバインディングを提供します。私はng-repeatを使用し続けるか、あるいは少なくとも何らかの形で双方向データバインディングを維持したいが、このinfdigサイクルを回避する。ベストプラクティスが無限にネストされたコメントであるか、またはAngularJSを最適化する方法について誰かが考えていますか?

+0

こんにちはフィリップ、私は以下の与えたすべてであなたを助けた答えをしていますか?ベスト、デュー – dewd

答えて

0

テンプレート内にng-repeatをラップするng-ifが見つからないようです。

変化:

<div ng-repeat="comment in comment.replies" ng-include="'commentTree'" style="margin-left:50px;"> 
</div> 

に:

<div ng-if="comment.replies.length"> 
    <div ng-repeat="comment in comment.replies" ng-include="'commentTree'" style="margin-left:50px;">   
    </div> 
</div> 

注何ら応答がない場合、これは、返信用の空の配列をとります。そこには応答がないと、空の応答配列が追加されていない場合、コードは次のようになります。

<div ng-if="comment.replies"> 
    <div ng-repeat="comment in comment.replies" ng-include="'commentTree'" style="margin-left:50px;">   
    </div> 
</div> 

例:https://plnkr.co/edit/B99uT2VBAKwpHzevjqip?p=preview

関連する問題