AngularJS: HTML选择使用map中的值,键按升序排列

AngularJS: HTML select to use values from map with ascending order on key

本文关键字:排列 升序 HTML 选择 map AngularJS      更新时间:2023-09-26

我有地图(双向)的状态。它由stateName和stateCode组成。它由以下HTML代码填充,但不能按stateCode或stateName升序进行过滤。

<div class="col-sm-2">
              <select ng-model="location.stateCode"  ng-change="loadDistricts();" ng-options="stateName for (stateCode, stateName) in stateOptions | orderBy:'stateCode'" class="form-control" id="state"></select>
</div>
//Json Object
    stateOptions = {'MH':'Maharashtra','GJ':'Gujarat','MP':'Madhya Pradesh'};

您倒置了stateCodestateName:

ng-options="stateName for (stateCode, stateName) in stateOptions"

另外,由于stateOptions是一个对象,键将可能按字母顺序插入,这取决于js虚拟机。orderBy过滤器在这里是没有意义的,因为(从文档中):

根据表达式谓词对指定数组排序。字符串按字母顺序排列,数字按数字顺序排列

<

看到strong>小提琴


Edit:如果你想控制顺序,把你的结构重做一个数组:

$scope.stateOptions = [{
    stateCode: 'MH',
    stateName:'Maharashtra'
},{
    stateCode: 'GJ',
    stateName:'Gujarat'
},{
    stateCode: 'MP',
    stateName:'Madhya Pradesh'
}];
ng-options="state.stateName for state in stateOptions | orderBy: 'stateCode'"

参见更新后的小提琴

另一种方式

    <select ng-model="location.stateCode" ng-change="loadDistricts();" 
     ng-options="stateName for (stateCode, stateName) in stateOptions | orderBy:'toString()' | filter:stateCode" 
     class="form-control" id="state">

如果我们不想重新构造对象,这也是一个很好的选择。首先根据键对映射对象进行排序,然后将其传递给ng-options。

$scope.stateOptions = sortObject($scope.stateOptions);
function sortObject(obj) {
            return Object.keys(obj).sort().reduce(function (result, key) {
            result[key] = obj[key];
            return result;
        }, {});}