Angularjs table sort with ng-repeat

后端 未结 3 734
难免孤独
难免孤独 2020-12-30 10:11

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

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-30 10:22

    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:

    
        {{ headers[$index] }}
    
    

    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:

    
        {{ headers[$index] }}
    
    

    Here is a fiddle with an example.

提交回复
热议问题