转发器中的重复项不允许使用angular.js

时间:2017-11-07 20:20:35

标签: javascript angularjs

我有一个视图控制器,其中包含以下代码,用于从api服务器获取数据:

$scope.recent_news_posts = localStorageService.get('recent_news_posts') || [];


        $http({method: 'GET', url: 'http://myapi.com/posts'}).success(function(data) {
            if ($scope.$$destroyed) {
                return
            }

            $scope.recent_news_posts = data || [];
            localStorageService.set("recent_news_posts", $scope.recent_news_posts);
        });

在模板中:

<md-card class="news-item" ng-repeat="post in recent_news_posts track by post.link" ng-click="openExternalLink(post.link);">
                    <md-card-title>
                        <md-card-title-text>
                            <span class="md-headline">{{ post.title }}</span>
                            <div class="md-subhead" ng-bind-html="post.content"></div>
                        </md-card-title-text>
                        <md-card-title-media>
                            <img src="{{ post.image }}" class="md-media-lg">
                        </md-card-title-media>
                    </md-card-title>
                </md-card>

有时我从哨兵那里得到报告:

  

[ngRepeat:dupes]不允许在转发器中复制。使用&#39;跟踪   由&#39;表达式以指定唯一键。中继器:发布   recent_news_posts track by post.link,Duplicate key:function link(),   重复值:

http://errors.angularjs.org/1.5.9/ngRepeat/dupes?p0=post%20in%20recent_news_posts%20track%20by%20post.link&p1=function%20link()&p2=%0A

我阅读了文章并添加了track by,但这没有任何帮助。 我想这可能是因为ng-repeat函数没有及时完成来自服务器的新数据。但不知道如何解决这个问题。

1 个答案:

答案 0 :(得分:0)

检查来自API的数据。可能有一些项目具有完全相同的post.link内部。如果您使用track,那么用于跟踪的项目必须是唯一的!