简体   繁体   中英

Sort by value in ng-repeat (key, value) pair from object

I'm new to AngularJS. Using API I am getting key - value pair with sports

$scope.sports = { 1: "Soccer", 2: "Tennis", 3: "Basketball" ... };

Is this possible to sort items by sport name:

<ul>
  <li ng-repeat="(id, value) in sports | orderBy:'value'">
      <a ng-href='/page/{{id}}'>{{value}}</a>
  </li>
 </ul>

this doesn't work at all

https://jsfiddle.net/ak657soa/1/

 now is
--------------------
    Soccer // id: 1
    Tennis // id: 2
    Basketball // id: 3
    MMA // id: 4
    Street dance // id: 5
    Aerobics // id: 6
    Aerial hoop // id: 7

should be
    --------------------
    Aerial hoop // id: 7
    Aerobics // id: 6
    Basketball // id: 3
    MMA // id: 4
    Soccer // id: 1
    Street dance // id: 5
    Tennis // id: 2

I tried to sort them inside controller with underscore.js (I used it in different view) but then I lose information about ids. Like here: https://jsfiddle.net/vmbme3yw/1/

How can I deal with orderBy value in AngularJs where are (key, value) pairs?

As the documentation says, orderBy expects an array as input, not an object.

Thus the solution is turning your object into an array. You can do this using reduce method by passing a callback function as argument .

$scope.sports = Object.keys($scope.sports).reduce(function(arr,key){
    arr.push({id: key, value: $scope.sports[key]})
    return arr;
},[]);

Also, you can use map method.

$scope.sports = Object.keys($scope.sports).map((key) => ({id: key, value: $scope.sports[key]}));

Now you can display your items ordered by value field.

<li ng-repeat="elem in sports | orderBy:'value'">
     <a ng-href='/page/{{elem.id }}'>{{elem.value}}</a> // id: {{id}}
</li>

Working solution:

 var app = angular.module('myApp', []); app.controller('myCtrl', function($scope) { $scope.sports = { 1: "Soccer", 2: "Tennis", 3: "Basketball", 4: "MMA", 5: "Street dance", 6: "Aerobics", 7: "Aerial hoop" }; $scope.sports = Object.keys($scope.sports).map((key) => ({id: key, value: $scope.sports[key]})); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-controller="myCtrl" ng-app="myApp"> <ul> <li ng-repeat="elem in sports | orderBy:'value'"> <a ng-href='/page/{{elem.id }}'>{{elem.value}}</a> // id: {{elem.id}} </li> </ul> </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