rakitin
rakitin

Reputation: 2185

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?

Upvotes: 8

Views: 21735

Answers (2)

rtucker88
rtucker88

Reputation: 986

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

Upvotes: 2

Amadan
Amadan

Reputation: 198436

<li ng-repeat="country in model.countriesVisited | orderBy:'toString()'">

Upvotes: 18

Related Questions