Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
33
rated 0 times [  37] [ 4]  / answers: 1 / hits: 21161  / 12 Years ago, fri, october 5, 2012, 12:00:00

I have an HTML table and want to sort my records ($scope.records in ctrl) by clicking on table headers ($scope.headers in ctrl),



Can anyone explain why does that work:



<th>
<a ng-click=sortColumn=headers[0];reverse=!reverse>{{ headers[0] }}</a>
</th>
<th>
<a ng-click=sortColumn=headers[1];reverse=!reverse>{{ headers[1] }}</a>
</th>


And that doesn't:



<th ng-repeat=header in headers>
<a ng-click=sortColumn=headers[$index];reverse=!reverse>{{ headers[$index] }}</a>
</th>


Here is the code for the records:



<tr ng-repeat=arr in records | orderBy:sortColumn:reverse>
<td ng-repeat=val in arr ng-bind-html-unsafe=arr[headers[$index]]</td>
</tr>


I have 58 columns in my table so would be much better to loop through the table headers...


More From » angularjs

 Answers
30

As David suggested this is likely scope related. Since ngRepeat creates a new scope your ngClick is setting the sortColumn and reverse in its own child scope for each column header.



One way around this to ensure you are modifying the values in the same scope would be to create a function on the scope and call that in your ngClick passing in the index:



$scope.toggleSort = function(index) {
if($scope.sortColumn === $scope.headers[index]){
$scope.reverse = !$scope.reverse;
}
$scope.sortColumn = $scope.headers[index];
}


with this as your markup:



<th ng-repeat=header in headers>
<a ng-click=toggleSort($index)>{{ headers[$index] }}</a>
</th>


Here is a fiddle with an example.






Another option would be to bind to a non-primitive type like this (the child scopes will be accessing the same object):



$scope.columnSort = { sortColumn: 'col1', reverse: false };


with this as your markup:



<th ng-repeat=header in headers>
<a ng-click=columnSort.sortColumn=headers[$index];columnSort.reverse=!columnSort.reverse>{{ headers[$index] }}</a>
</th>


Here is a fiddle with an example.


[#82736] Thursday, October 4, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raveno

Total Points: 453
Total Questions: 92
Total Answers: 92

Location: France
Member since Thu, Oct 27, 2022
2 Years ago
raveno questions
;