ngRepeat:dupes 即使通过 $index 跟踪(特殊情况) [英] ngRepeat:dupes even with track by $index (special case)

查看:36
本文介绍了ngRepeat:dupes 即使通过 $index 跟踪(特殊情况)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Brief background:- Am building a social networking site and am storing the statuses and users with MongoDB. So u have a status like this for example

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

现在在做 angular;

Now on angular am doing;

<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.

Note: All this works perfect

But here's is problem. Am using Websockets to automatically update and add the new statuses to $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['_id']

Now if you do a console.log() of 'status' inside the websocket callback, i get the status and it appears twice. In a sense that the websocket was sent twice (of which i have no control over). So when this is put inside "$rootScope.statuses" thats when i get the error "Error: [ngRepeat:dupes] Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys." It don't make sense because I am actually using $track by status['_id']

推荐答案

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

@BuddistBeast comment (underneath my question) lead me in the right path to fixing my problem. I ended up adding https://github.com/a8m/angular-filter plugin and using its "unique" filter provided therein. That fixed the ngRepeat dupes errors showing up. But then, I'd still see duplicated statuses appearing for some reason (but no error on the console). So if i post "hi" for example, i would see "hi" appearing twice. I did manage to fix it altogether, but the fix to that problem is separate and beyond the scope of this question.

这篇关于ngRepeat:dupes 即使通过 $index 跟踪(特殊情况)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆