Sorting dropdown alphabetically in AngularJS

前端 未结 4 1560
情话喂你
情话喂你 2020-12-07 15:19

I\'m populating a dropdown through the use of ng-options which is hooked to a controller that in turn is calling a service. Unfortunately the data coming in is a mess and I

相关标签:
4条回答
  • 2020-12-07 15:48

    You should be able to use filter: orderBy

    orderBy can accept a third option for the reverse flag.

    <select ng-option="item.name for item in items | orderBy:'name':true"></select>
    

    Here item is sorted by 'name' property in a reversed order. The 2nd argument can be any order function, so you can sort in any rule.

    @see http://docs.angularjs.org/api/ng.filter:orderBy

    0 讨论(0)
  • 2020-12-07 16:01
    var module = angular.module("example", []);
    
    module.controller("orderByController", function ($scope) {
        $scope.orderByValue = function (value) {
            return value;
        };
    
        $scope.items = ["c", "b", "a"];
        $scope.objList = [
            {
                "name": "c"
            }, {
                "name": "b"
            }, {
                "name": "a"
            }];
            $scope.item = "b";
        });
    

    http://jsfiddle.net/Nfv42/65/

    0 讨论(0)
  • 2020-12-07 16:01

    For anyone who wants to sort the variable in third layer:

    <select ng-option="friend.pet.name for friend in friends"></select>
    

    you can do it like this

    <select ng-option="friend.pet.name for friend in friends | orderBy: 'pet.name'"></select>
    
    0 讨论(0)
  • 2020-12-07 16:04

    Angular has an orderBy filter that can be used like this:

    <select ng-model="selected" ng-options="f.name for f in friends | orderBy:'name'"></select>
    

    See this fiddle for an example.

    It's worth noting that if track by is being used it needs to appear after the orderBy filter, like this:

    <select ng-model="selected" ng-options="f.name for f in friends | orderBy:'name' track by f.id"></select>
    
    0 讨论(0)
提交回复
热议问题