ng中的订单项重复跟随项目的属性

时间:2013-11-05 09:55:57

标签: angularjs angularjs-scope angularjs-ng-repeat angularjs-orderby

如何订购帖子自上而下的结构(最高likes号的帖子将是第一个,最后一个是最低likes个号码的帖子。要做到这一点,我设置oderBy:likes.length但它不起作用。请帮忙,谢谢!

 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>

1 个答案:

答案 0 :(得分: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>

这是一个有效的Fiddle