Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort an array of strings alphabetically with angular orderBy filter?

I have a model that contains a list of countries

$scope.model = {
    name: "foo",
    countriesVisited: ["CA", "AR", "GB", "FR", "MX", "AU", "IE", "RU", "IT", "ES", "IN", "US", "NL", "DE", "CL", "BR", "JP", "NZ", "PL"]
  }

Using an ng-repeat directive lists them in the order they are shown. Putting an orderBy filter does order the items, but the order is seemingly random. See this plunker

Remove the filter and watch the output shift. Paste it back and it's in a weird order.

Is there a way to get the countriesVisited array to order without moving it to it's own $scope variable?

like image 429
rakitin Avatar asked Oct 27 '14 02:10

rakitin


2 Answers

<li ng-repeat="country in model.countriesVisited | orderBy:'toString()'">
like image 118
Amadan Avatar answered Oct 09 '22 23:10

Amadan


Change your orderBy to orderBy: 'toString()'. Primitives don't sort by default, but you can pass in a function as we are doing here.

like image 21
rtucker88 Avatar answered Oct 10 '22 00:10

rtucker88