Search code examples
javascriptangularjsarraysangularjs-ng-repeatng-options

ng-repeat array order by the property index of datasource


I have an array source with nested arrays DataRows with no property name like that:

 $scope.arraySource = [
                      ["21", "Leon", "Blue"],
                      ["15", "Marcel", "Red"],
                      ["14", "Jason", "Yellow"],
                      ["25", "Luc", "Green"],
                      ["74", "Cyrile", "Black"],
                      ["45", "John", "Grey"],
                      ["21", "Etiennes", "Green"],
                      ["58", "Mario", "Pink"],
                      ["56", "Sylvain", "Blue"],
                      ["87", "John", "White"]
];

I would like use it in a ng-repeat and to order that data from the first, the second or the third property.

I would like to order by index of datasource and not by propertyName

It would be something like that:

<select ng-model="indexForSort"
        ng-select="idx for idx in [0,1,2]">
</select>   

 <table>
     <tr ng-repeat="row in arraySource   | 
                orderBy: indexForSort">
       <td>row[0]</td>
       <td>row[1]</td>
       <td>row[2]</td>
     </tr>
    </table>

if the user select 0 in dropdown list, it will sort table by age, if he select 1, it will sort by Name if he select 2, it will sort by Color

Do you know how to do this please?


Solution

  • index.html:

    <!DOCTYPE html>
    <html ng-app="MyApp">
    
    <head>
      <script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
      <script src="app.js"></script>
    </head>
    
    <body ng-controller="MainCtrl">
    
      <select ng-model="indexForSort" ng-options="idx for idx in [0,1,2]">
      </select>
    
      <table>
        <tr ng-repeat="row in arraySource | orderBy: ''+indexForSort">
          <td>{{row[0]}}</td>
          <td>{{row[1]}}</td>
          <td>{{row[2]}}</td>
        </tr>
      </table>
    
    </body>
    
    </html>
    

    app.js:

    var app = angular.module('MyApp', []);
    
    app.controller('MainCtrl', function($scope) {
    
      $scope.indexForSort = 0;
    
      $scope.arraySource = [
        ["21", "Leon", "Blue"],
        ["15", "Marcel", "Red"],
        ["14", "Jason", "Yellow"],
        ["25", "Luc", "Green"],
        ["74", "Cyrile", "Black"],
        ["45", "John", "Grey"],
        ["21", "Etiennes", "Green"],
        ["58", "Mario", "Pink"],
        ["56", "Sylvain", "Blue"],
        ["87", "John", "White"]
      ];
    });