0

$scope.units gives me the data like

[{"name":"unit 12: Abc","id":"K09A"},{"name":"Unit 4: Xyz","id":"C9J5"},{"name":"Unit 1: Acx","id":"X4C8"},{"name":"unit 4: Kxc","id":"W230"}, .....]


i use a filter to call the names in ng-repeat

ng-repeat="unit in units | orderBy: 'name'"

but it gives me the order of

Unit 1 , 10 , 11, 12, 2, 3, 4, 5, ..


I guess i need to parse or something. But i am unable to sort the issue. What changes can i make to get it in the integer order.

3
  • you need a custom filter that pulls the unit number out of the string and sorts numerically based on that number. blog.overzealous.com/post/55829457993/… Commented Oct 10, 2014 at 18:34
  • @KevinB no need for a custom filter, it's possible to use a getter function in the the orderBy filter. Have a look at my answer. Commented Oct 10, 2014 at 18:56
  • Sorry, i considered a custom filter or using a function to be pretty much the same thing. The article i linked to is infact using a function, not a custom filter. Commented Oct 10, 2014 at 18:58

2 Answers 2

4

You will need to create a getter function for the orderBy filter, like this:

Controller:

$scope.unitOrder = function(unit){ return parseInt(unit.name.split(' ')[1]);}

View:

ng-repeat="unit in units|orderBy:unitOrder"

Working Example

Sign up to request clarification or add additional context in comments.

Comments

1

if you don't mind modifying the original array you could just sort it manually. (and skip some extra dirty checking that runs twice)

$scope.units.sort(function(a, b) {
  return parseInt(a.name.split(' ')[1]) - parseInt(b.name.split(' ')[1]);
});

Comments

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.