我正在使用Rails gem gems_as_commentable_with_threading。效果很好。
我还在前端使用AngularJS。我有一个控制器,该控制器返回以下JSON以呈现要注释的内容:
[
{
"comment":{
"id":1,
"commentable_id":1,
"commentable_type":"Post",
"title":null,
"body":"This is a very cool comment!",
"subject":null,
"user_id":5,
"parent_id":null,
"lft":1,
"rgt":4,
"created_at":"2016-12-16 03:50:24",
"updated_at":"2016-12-16 03:51:24"
},
"children":[
{
"comment":{
"id":2,
"commentable_id":1,
"commentable_type":"Post",
"title":null,
"body":"I definitely think this is cool too.",
"subject":null,
"user_id":7,
"parent_id":null,
"lft":2,
"rgt":3,
"created_at":"2016-12-16 03:51:06",
"updated_at":"2016-12-16 03:51:24"
},
"children":[
]
}
]
}
]
如果有人选择回复ID为2的评论,则意味着新创建的评论将插入到children
所述评论的数组中。有没有用角度做到这一点的方法?还是我基本上会编写自己的递归函数,该函数循环遍历每个注释及其子对象,直到找到具有相同ID的注释对象并将新注释推入children数组中?
原因是我将通过websocket发送的单个评论发送给网站上的其他用户。
您可以将地图维护为注释嵌套数组的平面版本。您将需要递归地循环注释数组并将所有元素添加到地图(一次,在渲染注释之前)。
例如:
function addCommentsToMap(comments, commentsMap ) {
comments.forEach(function(comment) {
commentsMap[comment.id] = comment;
addCommentsToMap(comment.children, commentsMap );
});
}
var commentsMap = {};
addCommentsToMap(comments, commentsMap);
具有这样的映射使得仅需一个操作就可以插入注释。当有新评论时,您可以简单地输入:
commentsMap[parentCommentId ].children.push(newComment);
之后,newComment将出现在您的递归数组中,因为它由与地图相同的对象组成。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句