带有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.
推荐答案
已解决
所以要计算级别,我在响应的ng-repeat中使用了level变量:
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屋!