ngRepeat:即使通过 $index 进行跟踪也会被欺骗(特殊情况)

2024-03-07

简要背景:- 我正在构建一个社交网站,并使用 MongoDB 存储状态和用户。例如,你有这样的状态

{
    "status" : "Hello world.",
    "profileURL" : "ac271a307",
    "comments" : [ ],
    "time" : "2013-10-28T22:25:24.278Z",
    "active" : true,
    "owner" : DBRef("users", "[email protected] /cdn-cgi/l/email-protection"), // MongoDB Reference to the users Collection
    "_id" : ObjectId("526ee454da46f33bf8000002")
} 

现在在 Angular 上做;

<li ng-repeat="status in statuses | isUserStatus track by status['_id']" ng-show="status.active" class="user-status-bland">

    // In here i display the users data and the status itself.
</li>

注意:这一切都很完美

但问题就在这里。我使用 Websockets 自动更新并将新状态添加到 $rootScope.statuses 中。

socket.on('new status', function(status) {
    $timeout(function() {
        $rootScope.$apply(function() {
            // stack the new status at the top of all statuses.
            $rootScope.statuses.unshift(status);
        });
    }, 0);
})

现在,如果您在 websocket 回调中执行“status”的 console.log(),我会得到状态并且它会出现两次。从某种意义上说,websocket 被发送了两次(我无法控制)。因此,当将其放入“$rootScope.statuses”中时,我就会收到错误“错误:[ngRepeat:dupes] 不允许在转发器中重复。使用‘track by’表达式来指定唯一键。”这没有意义,因为我实际上正在使用 $track by status['_id']


@BuddistBeast 评论(在我的问题下面)引导我走上解决问题的正确道路。我最终添加了https://github.com/a8m/angular-filter https://github.com/a8m/angular-filter插件并使用其中提供的“独特”过滤器。这修复了出现的 ngRepeat dupes 错误。但是,我仍然会看到由于某种原因出现重复的状态(但控制台上没有错误)。因此,例如,如果我发布“hi”,我会看到“hi”出现两次。我确实设法完全解决了这个问题,但是对该问题的解决是单独的,超出了这个问题的范围。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ngRepeat:即使通过 $index 进行跟踪也会被欺骗(特殊情况) 的相关文章

随机推荐