Search code examples
javascriptangularjsng-options

Angular ng-options, sort object


I have an object which looks like:

{
   3019: 'Javascript',
   3046: 'Css'
}

and then, I show this object in a select like:

<select
    ng-model="langChoosed"
    ng-options="key as value for (key, value) in progLanguages"
></select>

I need to sort the items inside the select but the orderBy filter, seems to work only on arrays, how can I make it work with objects?


Solution

  • NO order by can't be applied to a plain object, alternatively you can define a method in the controller to convert the object to an array

    DEMO

    var app = angular.module('todoApp', []);
    
    app.controller("dobController", ["$scope",
      function($scope) {
        $scope.progLanguages = {
          3019: 'Javascript',
          3046: 'Css'
        };
        $scope.templatesAry = function() {
          var ary = [];
          angular.forEach($scope.progLanguages, function(val, key) {
            ary.push({
              id: key,
              lang: val
            });
          });
          return ary;
        };
      }
    
    ]);
    <!DOCTYPE html>
    <html ng-app="todoApp">
    
    <head>
      <title>To Do List</title>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script>
    
    </head>
    
    
    <body ng-controller="dobController">
      <select class="form-control" id="selection" ng-model="currentSelected" ng-options="selection.id as selection.lang for selection in templatesAry()  | orderBy:'lang'"></select>
    </body>
    
    </html>