0

I am using angular js ng-repeat and I want to show specific element first


For example I have this object

$scope.user = {
    age: {
        display: "Age",
        val: "21" 
    },
    firstName: {
        display: "First Name",
        val: "John" 
    },
    lastName: {
        display: "Last Name",
        val: "Smith" 
    },
}

And using ng-repeat like this.

<tr ng-repeat = "(key, value) in user">
    <td ng-model = "user[key].display"></td>
    <td ng-model = "user[key].val"></td>
</tr>

If I use ng-repeat, it shows age, firstName and lastName, but I want to show firstName in ng-repeat first.

Thank you.

Gor
  • 2,808
  • 6
  • 25
  • 46
  • have you tried changing to firsName be first? – Alvaro Silvino Sep 08 '15 at 16:07
  • https://docs.angularjs.org/api/ng/directive/ngRepeat you can use a track by option. and then just an extra key value to be the index or key you wan't to order by – eran otzap Sep 08 '15 at 16:09
  • It is because when I get information from server, it must contain a lot of data, I don`t know what I will get, but I want to show firstName first and then show other data. – Gor Sep 08 '15 at 16:11

2 Answers2

1

As explained in this answer, you cannot specify the order of keys in javascript. You have to restructure your data to an array if you want to guarantee a certain order.

Community
  • 1
  • 1
lex82
  • 11,173
  • 2
  • 44
  • 69
1

There is no ordering in js objects. But you can extract the firstName and do the rest after:

<tr>
  <td ng-model = "user[firstName].display></td>
  <td ng-model = "user[firstName].value></td>
</tr>
<tr ng-repeat = "(key, value) in user" ng-if="key!='firstName'">
  <td ng-model = "user[key].display"></td>
  <td ng-model = "user[key].val"></td>
</tr>
Diego Martinoia
  • 4,592
  • 1
  • 17
  • 36
  • Someone posted the option of specifying the order in the object. While this is a valid option in terms of result, I'd not recommend it, as it means putting view logic in the data layer! – Diego Martinoia Sep 08 '15 at 16:18