如何在单击按钮时使行更改颜色,并在再次单击时返回到原始颜色

时间:2020-03-27 00:31:28

标签: html css angularjs

单击按钮时,我要更改颜色,单击同一按钮时,我要返回原始颜色。现在,当单击按钮时,所有行都会更改颜色。

html

<table>
      <tbody ng-repeat="field in availableFields">
        <tr  ng-class="{'orderTypeTableRowSelected':tableRowTrueOrFalse}">
                <td style="padding:3px;">{{field.name}}</td>
                <td style="padding:3px;">
                <button type="button" ng-click="orderTypeTableRowSelected(field)" class="btn btn-danger" style="margin-left:10px;"><i class="fas fa-check"></i>&nbsp;Required</button>
        <button type="button" class="btn btn-warning"><i class="fas fa-check"></i>&nbsp;Default&nbsp;&nbsp;&nbsp;</button>
                </td>

    </tr>
    </tbody>
</table>

CSS

<style>

    .orderTypeTableRowSelected {
        background-color: #E0F7FA;
    }
</style>

角形

        $scope.tableRowTrueOrFalse = false;
        $scope.orderTypeTableRowSelected = function (field) {
            $scope.tableRowTrueOrFalse = !$scope.tableRowTrueOrFalse;
            console.log(field);
        };

1 个答案:

答案 0 :(得分:1)

这里的问题是您有一个值列表,但只有一个布尔值代表所有值。

tableRowTrueOrFalse应该是布尔值数组,而不是布尔值。然后,您应将false设置为默认数组。

$scope.tableRowTrueOrFalse = Array(availableFields.length).fill(false);

在您的html中,它将类似于:

<table>
      <tbody ng-repeat="field in availableFields">
        <tr  ng-class="{'orderTypeTableRowSelected':tableRowTrueOrFalse[$index]}">
                <td style="padding:3px;">{{field.name}}</td>
                <td style="padding:3px;">
                <button type="button" ng-click="orderTypeTableRowSelected(field, $index)" class="btn btn-danger" style="margin-left:10px;"><i class="fas fa-check"></i>&nbsp;Required</button>
        <button type="button" class="btn btn-warning"><i class="fas fa-check"></i>&nbsp;Default&nbsp;&nbsp;&nbsp;</button>
                </td>

    </tr>
    </tbody>
</table>

然后在您的函数中

$scope.orderTypeTableRowSelected = function (field, index) {
            $scope.tableRowTrueOrFalse[index] = !$scope.tableRowTrueOrFalse[index];
            console.log(field);
        };