0

How can I order the post to top-down structure (the post which has highest likes number will be first and the last is the post which lowest likes number). To do that I set oderBy:likes.length but it is not work. Please help, thanks!

 function MyController($scope) {
        $scope.posts = [{"title": "AAtitle",
                        "content":"AAcontent",
                        "likes":["person1", "person2", "person3"]
                       },
                       {"title": "BBtitle",
                        "content":"BBcontent",
                        "likes":["person10"]
                       },
                        {"title": "CCtitle",
                        "content":"CCcontent",
                        "likes":["person10","person11", "person100", "person1", "person2"]
                       }
                      ]
    }

    <div ng-controller = "MyController">
      <ul>
        <li ng-repeat = "post in posts | oderBy: likes.length">
               <div> {{post.title}} </div>
               <div> {{post.content}} </div>
               <div> {{post.likes.length}} </div>
        </li>
      </ul>
    </div>
4

1 回答 1

1

您可以编写一个函数来在控制器中进行排序,然后再显示在视图中。或者更可取的是,您可以编写一个自定义过滤器

筛选:

angular.module('YourAppName', [])
.filter('orderByLikes', function() {
    function compare(a, b) {
        return b.likes.length - a.likes.length;
    }
    return function (input) {
        return input.sort(compare);
    }
}); 

看法:

<div ng-controller = "MyController">
  <ul>
    <li ng-repeat = "post in posts | orderByLikes:posts">
           <div> {{post.title}} </div>
           <div> {{post.content}} </div>
           <div> {{post.likes.length}} </div>
    </li>
  </ul>
</div>

这是一个工作小提琴

于 2013-11-05T10:51:48.197 回答