Kofi
Kofi

Reputation: 39

Sorting item with checkbox checked at the top of the list in AngularJS

Im comparing two object arrays and displaying them with those that have the same object checkbox checked. I now want to sort the list the with checkbox check to be first as a default state. I also want to sort by clicking the header to sort by ascending order .

 <div>header</div>
    <div class="search" ng-repeat="items in products ">
        <label >{{item.name}}</label>

   <input type="checkbox" ng-model="item.checked" 
                          ng-click="checked(item,productlist)"
                          ng-checked=" checked(item,productlist)"> 
    </div>

I tried using orderBy:[‘-checked’,’item’]: true to sort the checked ones on top but its not working. Any ideas

Upvotes: 2

Views: 1625

Answers (1)

hayzey
hayzey

Reputation: 464

A few problems here...

  1. You have ng-repeat="items in products", but then you refer to item instead of items within this scope.

  2. You have this checked() method that you're passing to ng-click and ng-checked. What exactly is this doing? You should never be using ng-checked in conjunction with ng-model - https://docs.angularjs.org/api/ng/directive/ngChecked

  3. By passing '-checked' to orderBy, items will be ordered by their checked value in reverse, i.e. they will be ordered false first, true last. Then you're passing true as the reverse parameter to orderBy, so the list will be reversed again. You're reversing the ordering twice unnecessarily - https://docs.angularjs.org/api/ng/filter/orderBy

This might work better...

<div>header</div>
<div class="search" ng-repeat="item in products | orderBy: 'checked'">
    <label>{{item.name}}</label>
    <input type="checkbox" ng-model="item.checked">
</div>

Upvotes: 2

Related Questions