yuro yuro - 15 days ago 4
AngularJS Question

Sorting columns in nested ng-repeat (AngularJS)

Currently I don't have any possibility to sort the columns of my list by using the

orderBy
-filter. The problem what I have is a nested ngRepeat.

View:

<md-list>
<md-list-item>
<span ng-repeat="item in ::hItems track by $index" ng-click="sortBy(item)" flex>
{{ ::item }}
</span>
</md-list-item>
<md-divider></md-divider>
<md-list-item ng-repeat="cItem in ::cItems | orderBy:sortType:sortReverse track by $index">
<span ng-repeat="(key, value) in ::cItem track by $index" flex>
{{ ::value }}
</span>
<md-divider></md-divider>
</md-list-item>
</md-list>


As soon as the user click on a column header the function
sortBy
will be invoked. The function is implemented in the controller as follows:

//Default values:
$scope.sortType = 'NAME';
$scope.sortReverse = false;
var orderBy = $filter('orderBy');

//sortBy func:
function sortBy(columnKey) {
$scope.sortType = columnKey;
$scope.sortReverse = !$scope.sortReverse;
$scope.cItems = orderBy($scope.cItems, $scope.sortType, $scope.sortReverse);
}


The list sorts just by the default value
name
. Here is the array output of GET-request:

//JSON data
[
{
"ArtNo": "DE123",
"SHORTCODE": "ABC",
"NAME": "article one",
"QUANTITY": 3,
"GROUPID": 1,
"ACTIVE": 1
},...
]


So, I need nested ngRepeat because how you can see the array is defined with key numbers and object values =>
[0:Object, 1:Object...]
. I need just a solution for my
sortBy
-function. Have anyone an idea?

The following is my output list:

ArtNo | SHORTCODE | NAME | QUANTITY
DE123 | ABC001 | article one | 3
DE456 | ABC002 | article two | 8
DE789 | ABC003 | article three | 4
DE321 | ABC004 | article four | 13
....

Answer

If I understood right, you want this behavior:

  • User click on desired column to sort, and the table content will be ordered by that column.
  • User click again and the sort direction inverts.

Right?

So why are you ordering twice your array?

//Default values:
$scope.sortType = 'NAME';
$scope.sortReverse = false;
var orderBy = $filter('orderBy');

//sortBy func:
function sortBy(columnKey) {
    $scope.sortType = columnKey;
    $scope.sortReverse = !$scope.sortReverse;
    // You do not need to order anything here. Just define your orderby parameters here to be used on view.
}

Real solution

As talk with question author, we did found the main problem here:

The use of :: syntax on ng-repeat avoids angular from watching changes on OrderBy filter, so the change did not reflect on view.