0

Just getting into AngularJS and I have a simple question.

When there is an 'orderBy', the $index references the sorted array. What is the simplest way to reference back to the original array index before the sort.

<div ng-init="names=['Jack Doe','Dave Smith','Jone Johnson','Nancy Doe','Adam Smith']">
    <h3>Presenters</h3>
        <ul>
            <li ng-repeat="person in names | orderBy:'toString()'">
                [{{$index+1}} : {{person}}]
            </li>
        </ul>
</div>
2
  • I would have assumed that the process of ordering the array would fundamentally change it. What do you need the original index for? Commented Feb 20, 2014 at 15:55
  • Just stretching the legs to see what is possible. ng-repeat creates its own scope. The original array remains intact with the controller scope. Commented Feb 20, 2014 at 16:04

2 Answers 2

3

I've found my answer. It's fairly simple.

Since the original array is still intact and since AngularJS allows expressions in the binding, just a simple Javascript indexOf method does the trick.

<li ng-repeat="person in names | orderBy:'toString()'">
    [{{(names.indexOf(person)+1)}}  :  {{person}}]
</li>

Thanks.

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

Comments

2

If the original order has business meaning you could store it in your models.

function Person(name, order) {
    this.name = name || '';
    this.order = order;    
}

var names = ['Jack Doe', 'Dave Smith', 'Jone Johnson', 'Nancy Doe', 'Adam Smith'];

var people = [];
for(var i = 0; i < names.length; i++) {
    people.push(new Person(names[i], i + 1));
}

<li ng-repeat="person in people | orderBy:'name'">
    [{{person.order}} : {{person.name}}]
</li>

2 Comments

Thanks but too complicated. Not what I was looking for.
I myself would have already had that Person model set up, but yes, if you don't wrap data in business models then it is more complicated.

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.