How to sort an array of strings alphabetically using 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 the ng-repeat directive lists them in the order in which they are displayed. Putting an orderBy filter arranges the elements, but the order seems random. See plunker

Remove the filter and observe the output shift. Insert it back and it is in a weird order.

Is there a way to access the countriesVisited array without moving it to my $ scope variable?

+5
source share
2 answers
 <li ng-repeat="country in model.countriesVisited | orderBy:'toString()'"> 
+13
source

Change your orderBy to orderBy: 'toString ()'. Primitives do not sort by default, but you can pass a function as we do here.

+2
source

Source: https://habr.com/ru/post/1205572/


All Articles