1

I have created a Angular Select box for countries. My array looks like this:

AD: "Andorra"

AE: "United Arab Emirates"

AF: "Afghanistan"

AG: "Antigua and Barbuda"

AI: "Anguilla"

And my NgRepeater looks like this

<li nya-bs-option="(k, v) in fields.country.available" data-value="v" data-label="{{v}}">

As you can see, The 'Key' is automatically getting alphabetically arrange in order. However I wish for the 'Value' to be arranged in alphabetical order. I have tried:

<li nya-bs-option="(k, v) in fields.country.available | orderBy:'v'" data-value="v" data-label="{{v}}">

But this didn't work. Can anyone help?

Richy
  • 167
  • 3
  • 13

2 Answers2

0

Your array seems more like an object as far as I can see from <key>:<value> structure. In this case you would need to write an own filter for orderBy because angular cannot sort object keys with this filter.

See also: Order by Object key in ng-repeat

Despite of the solution in the thread above, I would suggest to use another structure for the countries if possible:

[{id: 'AD', name: 'Andorra'}, ...]

Then you can do this in ng-repeat:

country in fields.country.available | orderBy: 'id'
Community
  • 1
  • 1
FlorianTopf
  • 938
  • 6
  • 10
  • Unfortunately I am unable to do this, as the data is being produced from Moltin API. – Richy Nov 22 '15 at 21:30
  • see my updated answer. This might work for you, since it is done without transforming the original object. – FlorianTopf Nov 22 '15 at 21:43
  • Gave it a whirl but getting 'Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!' – Richy Nov 22 '15 at 22:15
  • Sorry, I would have seen this if I tried it by myself. It cannot work becasuse $digest() is fired on each iteration by applying the filter. I removed my update to avoid confusion. The quickest way is still to manipulate the original datastructure. is there no possibility to save the API response in the scope to a new structure? – FlorianTopf Nov 22 '15 at 22:53
0

I have solved it. And by doing this way, the countries are automatically put into alphabetical order :)

HTML:

<ol class="nya-bs-select" ng-model="data.ship.country" name="ship_{{fields.country.slug}}">
    <li nya-bs-option="v in sortable" data-value="v[0]">
        <a>{{v[1]}}</a>
    </li>
</ol>

Controller:

var countries = fields.country.available,
    sortable = [];

for (var country in countries){
  sortable.push([country, countries[country]]);
}       
sortable.sort(function(a, b) {
  return a[1] - b[1]
});

$scope.sortable = sortable;
Richy
  • 167
  • 3
  • 13