northsideknight
northsideknight

Reputation: 1557

How to move an item to front of list in Angular 1

In our database, we have a given object that a user can have many of, but 1 is marked as primary. In our Angular 1 app, we list these objects but we always want to show the object marked as primary first.

So we have our list of these objects...

<object-of-interest ng-repeat="obj in objs"></object-of-interest>

The object in json form would look like this if it was the primary object:

{
  attr_1: value,
  attr_2: value,
  ...
  primary: true
}

or else the primary attribute would be set to false.

I am wondering what the best way is to move the primary object to the front of the array?

The only way I can seem to find online would be to remove the object from the array then use the unshift method to put it in the front of the array, but that seems unclean to me.

Thanks for the help!

Upvotes: 0

Views: 101

Answers (2)

JanS
JanS

Reputation: 2075

You can use the orderBy filter:

<object-of-interest ng-repeat="obj in objs | orderBy:'-primary'"></object-of-interest>

Here's an adapted Plunker from Angular's documentation: http://plnkr.co/edit/T0h4JenpefWYXnul1U3J?p=preview

The documentation can be found here: https://docs.angularjs.org/api/ng/filter/orderBy

Upvotes: 1

Arcagully
Arcagully

Reputation: 364

There are 2 ways you can resolve this issue, first is to reorder collection before you display it and this is also most proper way.

Second way is with using additional ng-repeat with ng-show ir ng-if, and this is bad solution.

<object-of-interest ng-repeat="obj in objs" ng-show="obj.primary == true"></object-of-interest>
<object-of-interest ng-repeat="obj in objs" ng-show="obj.primary == false"></object-of-interest>

I advise you to use first solution, that is, to reorder collection once you received it from API!

Upvotes: 0

Related Questions