使用 ng-repeat 在 AngularJS 中嵌套注释 [英] Nested comments in AngularJS with ng-repeat
问题描述
我创建了一个指令,用于在 AngularJS 中显示嵌套注释.当从 API 返回的 JSON 看起来像这样时,它的要点是有无限的注释:
I've created a directive for displaying nested comments in AngularJS. The main point of it was to have infinite comments when returned JSON from API would look something like this:
[
{
'id': 66,
'text': 'This is the first comment.',
'creator': {
'id': 52,
'display_name': 'Ben'
},
'respondsto': null,
'created_at': '2014-08-14T13:19:59.751Z',
'responses': [
{
'id': 71,
'text': 'This is a response to the first comment.',
'creator': {
'id': 14,
'display_name': 'Daniel',
},
'respondsto': 66,
'created_at': '2014-08-14T13:27:13.915Z',
'responses': [
{
'id': 87,
'text': 'This is a response to the response.',
'creator': {
'id': 52,
'display_name': 'Ben',
},
'respondsto': 71,
'created_at': '2014-08-14T13:27:38.046Z',
'responses': []
}
]
}
]
},
{
'id': 70,
'text': 'Đây là bình luận thứ hai.',
'creator': {
'id': 12,
'display_name': 'Nguyễn'
},
'respondsto': null,
'created_at': '2014-08-14T13:25:47.933Z',
'responses': []
}
];
所以在第一级,我在这个数组上做 ng-repeat:
So on the first level I'm doing ng-repeat on this array:
<div ng-repeat="comment in comments | orderBy: 'id': true" ng-include="'comment.html'"></div>
然后在 comment.html 里面我用相同的模板重复响应:
And then inside of comment.html I'm repeating responses with the same template:
<div ng-repeat="comment in responses = comment.responses | orderBy: 'created_at': true" ng-include="'comment.html'"></div>
当有 10 个响应嵌套时,这给了我错误:
And this gives me erros when there are 10 nests of responses:
Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
现在我真的不需要解决这个错误,但我的问题是,我怎么知道我在哪个巢穴中,这样我就可以禁用添加新的响应,例如到达巢的第 5 层.
Now I don't really need to solve this error, but my question would be, how could I know in which nest I am so that I could disable adding new responses when e.g. 5th level of the nest is reached.
推荐答案
SOLVED
所以为了计算级别,我在响应的 ng-repeat 中使用了级别变量:
SOLVED
So to count levels I'm using level variable inside ng-repeat of responses:
<div ng-repeat="comment in responses = comment.responses | orderBy: 'created_at': true" ng-include="'comment.html'" ng-init="level = level + 1"></div>
然后在控件上我正在检查该级别,例如不显示控件:
And then on the controls I'm checking that level, e.g. to not show the control:
ng-hide="level > 5"
这篇关于使用 ng-repeat 在 AngularJS 中嵌套注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!