简体   繁体   中英

angular filter orderBy:key not working in angular js?

I am trying to displaying countries name in one select box and states name other select box , country name not coming acceding order, what can i do, please help me, i tried code bello code.

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>

script:

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";
});

The code:

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

will not work, because the built-in orderBy filter will no longer work when iterating an object. It's ignored due to the way that object fields are stored.

So you can transferm your object into an array something like this:

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

And then use:

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

The plunkr that can help (not created by me):

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

Let me know if you face any issue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM