8

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?

2 Answers 2

18
<li ng-repeat="country in model.countriesVisited | orderBy:'toString()'">
Sign up to request clarification or add additional context in comments.

1 Comment

Since values are already strings, isn't there a less greedy way to sort them? I'm just curious
2

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

2 Comments

ok - to clarify, this is converting each item in the array from a string type to a string object, correct? Why is it that primitives do not sort by default? I have read about the difference between string and String but never come across it in practice before - Thanks for the help!
The orderBy filter is expecting an object. Check out the documentation at https://docs.angularjs.org/api/ng/filter/orderBy. You'll see three options are available for the expression: a string of the value to sort on, function, or an array of string or functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.