1
I have an array with this form

$vars[1][1]["name"]     = "John";
$vars[1][1]["lastname"] = "Doe";
$vars[1][2]["name"]     = "Ely";
$vars[1][2]["lastname"] = "Tim";


$vars[2][1]["name"]     = "Brad";
$vars[2][1]["lastname"] = "Vinnie";
$vars[2][2]["name"]     = "Angelina";
$vars[2][2]["lastname"] = "Van";

.....

$vars[10][1]["name"]     = "Ela";
$vars[10][1]["lastname"] = "Pearl";
$vars[10][2]["name"]     = "Gustavo";
$vars[10][2]["lastname"] = "Tim";

which is in PHP. After that I send it to angularJS and i have

$scope.varArr = data.vars

after that in view I have

<div ng-repeat="(key, det) in varArr| orderBy: key">
     {{det.name}} {{det.lastname}}
 </div>

The problem is that it's not taking the array in the order 1,2,3...10

It's taking $vars[1] after that $vars[10] and after that $vars[2]. Instead of making the order after the number it's making after the string.

This situation is only if I have $vars[1][1] and $vars[1][2]...etc

If I would have only $vars[1][1], $vars[2][1], .... $vars[10][1] it will take the order after the number.

Developer
  • 21
  • 1

2 Answers2

0

In the Angular doc, it says that when you use the (key, value) method:

You need to be aware that the JavaScript specification does not define the order of keys returned for an object. (To mitigate this in Angular 1.3 the ngRepeat directive used to sort the keys alphabetically.)

Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser when running for key in myObj. It seems that browsers generally follow the strategy of providing keys in the order in which they were defined, although there are exceptions when keys are deleted and reinstated. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_issues

If this is not desired, the recommended workaround is to convert your object into an array that is sorted into the order that you prefer before providing it to ngRepeat. You could do this with a filter such as toArrayFilter or implement a $watch on the object yourself.

One way to handle this is to flatten the array into a single dimension before passing it to the document. This SO question has several answers on how to "flatten" a multidimensional array in PHP.

Community
  • 1
  • 1
jwatts1980
  • 7,254
  • 2
  • 28
  • 44
  • I've changed the AngularJS version from 1.3 to 1.4 and now it's working, but I've put
    and it's not making the order descending
    – Developer Jun 10 '15 at 16:48
0

Apostrophes missing:

<div ng-repeat="(key, det) in varArr| orderBy: 'key'">

without apostrophes Angular is looking for function 'key' in your controller, which does not exist neither

Dmitri Algazin
  • 3,332
  • 27
  • 30