AngularJS [无限摘要周期]中无限嵌套注释的渲染视图

时间:2016-05-21 16:04:51

标签: javascript angularjs recursion

我目前正试图无限制地嵌套评论(及其回复),类似于Reddit。

我目前有一般形式的大型结构:

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

由于所有评论都遵循一般div template并且他们的回复仅为margin-left:50px;,我遵循本教程使用递归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的优化程度非常低,而且由于我所拥有的嵌套infdig,我得到ng-repeat错误周期。这很奇怪,因为我确定它不是由我的评论数量引起的,而是我嵌套ng-repeats的事实。但是,它确实提供了非常有用的数据绑定。我希望继续使用ng-repeat或者至少以某种形式维护双向数据绑定,但要避免这个infdig周期。有没有人对最佳实践是无限嵌套注释或如何为此优化AngularJS有任何想法?

1 个答案:

答案 0 :(得分:0)

您似乎错过了ng-if包裹模板中的ng-repeat

变化:

 <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