我在AngularJS中有一个表,其中有几列可以按升序和降序排序。我想在用户点击它时选择一行。我通过获取表的选定索引来完成此操作。但是,一旦我使用其中一列,所选行仍会突出显示。我想要做的是保持先前选择的项目突出显示...无论其新索引可能在诉诸之后。这是一段代码:
我的桌子身体:
<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>
设置所选行的方法:
function setClickedRow(index) {
vm.selectedRow = index;
}
答案 0 :(得分:1)
您可以将selected
添加到item
,并在点击时将其设置为true(如果您想在点击时切换选择,则将其设置为!item.selected
)
<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;
}
答案 1 :(得分:1)
根据Slonski answer,我建议您在更改选择时循环显示所有项目以设置selected = false
:
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;
}
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>