user3531149 February 2016

How to sort this object by name in angular

My client needs an angular js app, the app is based on an api, of an app that's already running. one of the apis, returns a json structured like this:

{  
   "groups":{  
      "60":{  
         "name":"History"
      },
      "74":{  
         "name":"Discover our offers"
      },
      "109":{  
         "name":"Relaxing"
      }
   }
}

so we fetched the data on a controller this way:

  $http({method: 'GET', url: restUrl}).
      then(function(response)
      {
          $scope.poi_groups = response.data.groups;
      });

and display it on the view:

<ul class="content-menu">
    <li ng-repeat="(key, value) in poi_groups">
        <div><a ng-href="/poi/data/{{ key }}">{{ value.name }}</a></div>
    </li>
</ul>

What I've been struggling with is ordering the items by name, right now its being displayed exactly the way its returned on the json. How can I do something like:

(...)
<li ng-repeat="(key, value) in poi_groups | orderBy: value.name">
(...)

Answers


STEVER February 2016

use ngRepeat orderBy

Use filter like orderBy: 'name'

 <li ng-repeat="(key, value) in poi_groups| orderBy:'name'">

and

 <li ng-repeat="(key, value) in poi_groups| orderBy:'name': -1">

for DESC

if you make plnk we can check it out


Walfrat February 2016

This structure isn't appropriate for angularjs, either :

  1. Do it yourself in the .then method
  2. Write your own filter
  3. Map your object in a new one in the .then method to make it look like this :

    [{ value:'60', name:'History' }, { .... }]

Then you can use angular filtering.

Post Status

Asked in February 2016
Viewed 2,040 times
Voted 7
Answered 2 times

Search




Leave an answer