3

I am using the ng-options="ref as display for (ref, display) in syntax to display a non-array object as a dropdown, but am having trouble ordering the dropdown values.

How should I use the orderBy filter to sort this dropdown by display value?

    <div ng-controller="MyCtrl">
      <select name="category" type="text" ng-model="categories " ng-options="ref as display 
for (ref, display) in categories | orderBy:'display'" >

    </div>

    var myApp = angular.module('myApp',[]);
    function MyCtrl($scope) {
      $scope.categories = {
          cat2: "Category 2",
          default: "anone",
          zone: "zone",
        };
    }

http://jsfiddle.net/ADukg/13412/

3
  • orderBy doesn't work for objects. You could convert your categories object to an array or you can implement a custom filter like this person: https://stackoverflow.com/a/18186947/2506481. This is a possible duplicate of that question Commented Jul 25, 2017 at 18:32
  • @ero thanks. when I add a custom filter, as in the answer you linked the drop-down displays as desired, but it seems the model is now tied to the newly created array. When I select an item, the model value is 0,1,or2 as opposed to cat2,default, or zone. Any suggestions as to how I can customize the drop-down ordering without changing the bound model? Commented Jul 25, 2017 at 19:41
  • @ero, nevermind, I see this is addressed in that answer's comment thread. Commented Jul 25, 2017 at 19:58

1 Answer 1

0

Orderby 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 myApp = angular.module('myApp',[]);
myApp.controller('myCtrl', function($scope) {
  $scope.categories = {
      cat2: "Category 2",
			default: "anone",
			zone: "zone",
	};
  
   $scope.templatesAry = function() {
      var ary = [];
      angular.forEach($scope.categories, function(val, key)
      {       
        ary.push({
          "category": val          
        });
      });
      return ary;
    };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
   <select class="form-control" id="selection" ng-model="currentSelected" ng-options="selection.category as selection.category for selection in templatesAry()  | orderBy:'category'"></select>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.