1

I need to loop trough object of users but I want to place a concrete user (me) at the beginning.

Example

this.users = [
    {
        id: 1,
        name: "Jane"
    },
    {
        id: 2,
        name: "John"
    },
    {
        id: 3,
        name: "Me"
    },
    {
        id: 4,
        name: "Mark"
    }
];

<div ng-repeat="user in ctrl.users">
    <!-- SOME OTHER TAGS -->
</div>

And I want it to be this

<div>
    <!-- ME -->
</div>

<div>
    <!-- JANE -->
</div>

<div>
    <!-- JOHN -->
</div>

<div>
    <!-- MARK -->
</div>

Is it posible to do it using orderBy or do I have to reorganize my array of users ?

Stevik
  • 1,092
  • 2
  • 16
  • 37

1 Answers1

2

You can use a custom function to do the sorting, see this fiddle

$scope.sortUsers = function (user) {
    if (user.name === 'Me') {
        // return blank so it's always first in the order
        // you can also do 'return 0'; if the sorting is by ID.
        return ''; 
    }

    // return user.id; if by sorting is by ID
    return user.name;
};

Use this in the view

<div ng-repeat="user in users | orderBy: sortUsers">
    {{user.name}}<br/>
</div>

For more information, you can also look at this thread and the docs.

Community
  • 1
  • 1
khakiout
  • 2,372
  • 25
  • 32