简体   繁体   中英

Angularjs ng-repeat with conditions

Lets say I have 10 articles objects array and each with their own article title in it ( assume some of them has the same title )

when i do ng-repeat="art in articles" and {{ art.article_title }} it will print the title 10 times which is not what I want.

I want to do something like

Title-1: article 1 article 2 article 3

Title-2: article 4 article 5......

something like that if articles share the same title.

Thanks

You should write a custom filter , then you will be able to proceed like this:

<li ng-repeat="unique_article in articles|dedup">
    {{unique_article.article_title}}
    <span ng-repeat="related in unique_article.related">
        Article {{related.id}}
    </span>
</li>

Your filter may look for example like this (assuming your articles are sorted by title):

.filter('dedup', function() {
  return function(articles) {
    var deduped = [];
    var last_article = null;
    for(var i=0,max=articles.length;i<max;i++) {
        var article = articles[i];
        if(!last_article || last_article.article_title !== article.article_title)
        {
            article.related = [];
            deduped.push(article);
            last_article = article;
        } else {
            last_article.related.push(article);
        }
    }
    return deduped;
  };
});

(I did not test it, just written it ad hoc as a quick example, also if your articles are not sorted by title you will have to modify it)

Maybe re-thinking it would help, the ideal way to do this would be to re-arrange your object so that the articles fall under the titles, like so.

var arrangeArticles = function() {
    var result = {};
    angular.forEach($scope.articles, function( article ) {
       var title = article.article_title;
       if( !result[title] ) {
         result[title] = [article];
       } else {
         result[title].push(article);
       }
    });
    $scope.articles = result;
    $scope.$apply(); // Might be needed 
};

I don't think that you can do this in the ng-repeat , with the layout that you expressed.

Then you would need to change your repeat to something like this

<div ng-repeat="(title, group) in articles">
    {{title}}
    <div ng-repeat="article in group">
       {{article.description}}
    </div>
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM