简体   繁体   中英

How to use AngularJS orderBy

I think my syntax is incorrect? Can I do this in Angular. The top two filters work but not the order bys

<div class ="col-md-8 pull-left">
      <span ng-click="myFilter = {green: true}">Clean</span>  |
      <span ng-click="myFilter = {green: false}">Dirty</span> |
      <span ng-click="myFilter = orderBy: 'governance' : true">Goverance</span> |
      <span ng-click="myFilter = orderBy: 'environmental' : true ">Environmental</span> |
      <span ng-click="myFilter = orderBy: 'community' :true">Community</span> |
      <span ng-click="myFilter = null">All</span>
</div>

<div class="list-group-item col-md-8 pull-left" ng-repeat="site in list.links | filter:myFilter">
{{site.governance}}
{{site.environmental}}
{{site.community}}
</div>

An example object is

{
      name: 'Facebook',
      url: 'www.facebook.com',
      green: false,
      governance: 45,
      environment: 69,
      community: 72,
      rank: 6
    }

You got the syntax wrong, you cannot set it that way, filter and orderBy are two different filters and take 2 different expressions. Instead set an order variable on click.

<div class ="col-md-8 pull-left">
     ...
      <span ng-click=" order='governance' ">Goverance</span> |
      <span ng-click=" order='environmental' ">Environmental</span> |
      <span ng-click=" order='community' ">Community</span> |
     ...
</div>

and use the variable:-

ng-repeat="site in list.links | filter:myFilter |orderBy:order"

and probably with a sort as well:-

 <span ng-click=" order='governance'; sort=!sort ">Goverance</span>
....
<div .. ng-repeat="site in list.links | filter:myFilter |orderBy:order:sort"

Plnkr

As PSL said you can do it by setting a variable upon click, the using that variable in the orderBy clause.

Here is a working fiddle

<div>
  <span ng-click="myFilter = {green: true}">Clean</span>  |
  <span ng-click="myFilter = {green: false}">Dirty</span> |
  <span ng-click="myOrder = 'governance'">Goverance</span> |
  <span ng-click="myOrder = 'environmental' ">Environmental</span> |
  <span ng-click="myOrder = 'community'">Community</span> |
  <span ng-click="myFilter = null">All</span>
</div>

<div class="list-group-item col-md-8 pull-left" ng-repeat="site in list.links | filter:myFilter | orderBy:myOrder"></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