Pregunta

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>
¿Fue útil?

Solución

You could write a function to do the sorting in the controller before displaying in view. Or preferable, you could write a custom filter

Filter:

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

View:

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

Here is a working Fiddle

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top