【发布时间】:2015-06-12 08:31:39
【问题描述】:
所以我有一个应用程序,它使用 socket.io 实时更新数据并使用 Angular JS 显示它。
我让它在多个 ng-repeats 中显示数据 (cmets),这些 ng-repeats 使用“track by”来确保在引入最新数据时忽略重复项。我还使用 LimitTo 仅显示一定数量的cmets 一次,LimitTo 是动态的,并在用户单击按钮时增加。
HTML
<div ng-controller="CommentsController" >
<!-- Comment Repeater Starts Here -->
<div ng-repeat="comment in comments | limitTo: limit track by comment.id" >
{{ comment.comment }}
<!-- Nested Reply Comments Start Here -->
<div ng-repeat="reply in comment.replies | limitTo: comment.limit track by reply.id" >
<div class="comment-text" >
{{ reply.comment }}
</div>
</div>
<a href="#" ng-click="increaseReplyLimit(comment, comment.limit)" ng-show="hasMoreComments(comment.replies, comment.limit)" >View More Replies</a>
</div>
<a href="#" ng-click="increaseLimit(limit)" ng-show="hasMoreComments(comments,limit)" >View More Comments</a>
对于我的第一个 ng-repeat,它工作得非常好,因为我将 LimitTo 分配给范围上的一个变量,当我通过 Socket.io 引入新数据时,该变量不受影响。 不过,对于我的嵌套 ng-repeat,我使用 comment.limit 作为 LimitTo 的变量,每次我通过 socket.io 引入新数据时,它都会被覆盖。(新数据有一个默认的comment.limit - 我之前尝试将其留空,但没有显示)。
角度
app.controller('CommentsController', function ($scope,socket,$http,$location) {
// fetching the latest comments from the API location
$http.get( $url + 'comments').success(function(comments) {
if (comments) {
$scope.comments = comments;
}
});
// updating comments via socket.io
socket.on('comment.update', function (data) {
$scope.comments = JSON.parse(data);
});
$scope.limit = 2;
$scope.hasMoreComments = function(comments, limit) {
if (typeof comments != "undefined" && comments != "false") {
var $commentLength = comments.length;
if ($commentLength > limit) {
return true;
}
return false;
}
return false;
}
$scope.increaseLimit = function(limit) {
$scope.limit = $scope.limit + 2;
}
$scope.increaseReplyLimit = function(comment, limit) {
comment.limit = parseInt(limit) + 2;
}
});
当我从 socket.io 引入新数据时,如何防止每个嵌套重复的当前限制被覆盖?
我已经尝试对新旧数据进行深度合并(想法是更新新数据中的嵌套限制以反映当前的嵌套限制)。但是,当我这样做时,Angular 完全忽略了新的限制,不再对嵌套的 cmets 实施任何限制。
引入的数据结构
[
{
"topics": [
{
"id": 75,
"topic": "test",
"approved": 1,
"created_at": "-0001-11-30 00:00:00",
"updated_at": "-0001-11-30 00:00:00",
"slug": "test",
"blurb": null
}
],
"id": 849,
"user_id": 80,
"news_id": 9,
"context": "Test News Article 1",
"comment": "<p>test comment 4</p>",
"origin": "Test",
"origin_url": "http://localhost:8000/news/test-news-article-1",
"author": "omurphy27",
"author_url": null,
"votes": 0,
"created_at": "2015-06-08 22:36:53",
"updated_at": "2015-06-08 22:36:53",
"approved": 1,
"slug": "test-comment-116",
"original": 1,
"parent_id": null,
"username": "omurphy27",
"limit": 2,
"voted": false
}
]
用这个把我的头撞在墙上已经有一段时间了,非常感谢任何帮助。
【问题讨论】: