角度过滤器orderBy:键不能在角度js中工作?

时间:2017-04-21 06:06:16

标签: javascript angularjs

我正在尝试在一个选择框中显示国家/地区名称并说明其他选择框名称,国家/地区名称未加入订单,我该怎么办,请帮助我,我尝试了代码bello代码。

HTML:

---
<div ng-app="myApp" ng-controller="myCtrl">
<div>
  <select id="country" style="width:250px;" class="" name="countryName" ng-model="state1" ng-change="displayState(state1)" ng-required="true">
                           <option ng-repeat="(key,country) in countries | orderBy:key"  value="{{key}}">{{country[0]}}</option>
                    </select>

</div>{{countries}}{{state1}}

<div><select id="state" ng-model="cities">
 <option ng-repeat="(state,city) in states[state1]" value="{{city}}">{{city}}</option></select></div>
</div>

脚本:

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $scope.states =  {
     "IN":[
       "Delhi",
       "Goa",
       "Gujarat",
       "Himachal Pradesh",
     ],
     "AU":[  
      "Australian Capital Territory",
      "New South Wales",
      "Northern Territory"
      ]
   };
   $scope.countries =  {
      "IN": ["India"],
       "ZA": ["South Africa"],
       "AU": ["Austria"],
       "BG": ["Bulgaria"],
            "RW": ["Rwanda"]
     }
    $scope.lastName = "Doe";
});

1 个答案:

答案 0 :(得分:2)

代码:

<option ng-repeat="(key,country) in countries | orderBy:key"  value="{{key}}">{{country[0]}}</option>

不起作用,因为迭代对象时内置的orderBy过滤器将不再起作用。由于存储了对象字段的方式,它被忽略了。

所以你可以把你的对象转移到这样的数组中:

$scope.countriesArray= [];
angular.forEach($scope.countries, function(value, key) {
    $scope.countriesArray.push({
        NewKey: key,
        NewValue: value
    });
});

然后使用:

<li ng-repeat="country in countriesArray | orderBy:'NewKey'">  
</li>

可以帮助的傻瓜(不是我创造的):

http://plnkr.co/edit/fSjledOzPqm6LzGtmCt9?p=preview

如果您遇到任何问题,请告诉我

相关问题