YourReflection
YourReflection

Reputation: 395

Keep selected element highlighted after resorting table

I have a table in AngularJS with several columns that can each be sorted ascending and descending. I want a row to be selected whenever a user clicks on it. I do this by getting the selected index of the table. However, once I resort one of the columns, the selected row remains highlighted. What I want to do is to keep the previously selected item highlighted...whereever its new index may be after the resorting. Here is a code snippet:

My table body:

<tbody>
    <tr
      ng-class="{'selected':$index == list.selectedRow}"
      ng-repeat="item in list.itemList | order:list.orderBy:list.orderAsc">
      <td ng-click="list.select(item);list.setClickedRow($index)">{{ item.number }}
      </td>
      <td ng-click="list.select(item);list.setClickedRow($index)">{{ item.name }}
      </td>
    </tr>
</tbody>

The method for setting the selected row:

function setClickedRow(index) {
    vm.selectedRow = index;
}

Upvotes: 0

Views: 603

Answers (2)

Mistalis
Mistalis

Reputation: 18309

Based on Slonski answer, I suggest you to loop over all items to set selected = false when you change your selection:

function setClickedRow(item) {
  for(var i = 0; i < $scope.list.itemList.length; i++) {
    if(item == $scope.list.itemList[i]) item.selected = true;
    else $scope.list.itemList[i].selected = false;
  }
  item.selected = true;
}

Update: Solution without a loop

var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl', ['$scope', function($scope) {
  $scope.setMaster = function(section) {
    $scope.selected = section;
  }

  $scope.isSelected = function(section) {
    return $scope.selected === section;
  }
}]);
.active {
    background-color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp" ng-controller="MyCtrl">
    <table>
      <tr ng-repeat="i in ['One', 'Two', 'Three']" ng-class="{active : isSelected(i)}">
        <td ng-click="setMaster(i)">{{i}}</td>
      </tr>
    </table>
    <hr> {{selected}}
</div>

Upvotes: 1

Slonski
Slonski

Reputation: 834

You can add selected to your item, and the set it to true on click (or set it to !item.selected if you want to toggle selection on click)

<tbody>
<tr
  ng-class="{'selected':item.selected}"
  ng-repeat="item in list.itemList | order:list.orderBy:list.orderAsc">
  <td ng-click="list.select(item);list.setClickedRow(item)">{{ item.number }}
  </td>
  <td ng-click="list.select(item);list.setClickedRow(item)">{{ item.name }}
  </td>
</tr>
</tbody>



function setClickedRow(item) {
  item.selected = true;
}

Upvotes: 1

Related Questions