简体   繁体   中英

change css of single cell(td) in table angularjs

Problem: Using AngularJS, I need to change the color(or we can say CSS) of a single cell(td) on which user has clicked.

For now to simplify the use case, just want to change color of all table cells where we have zero

Below is the code which I have tried, but its changing the color of all the cells in table.

<body ng-controller="MainCtrl">
    <table>
      <tbody>
        <tr ng-repeat="row in tableType.data.rows track by $index">
          <td ng-repeat="col in row track by $index" >
            <span id={{col}} ng-class='cellColor' ng-click='updateCellColor(col)'>{{col}}</span>
          </td>
        </tr>
      </tbody>
    </table>
  </body>

Contoller

app.controller('MainCtrl', function($scope) {
  $scope.tableType = {
    data: {
      rows: [
        ["69123", 20, 20, 40, 0, 0, 0, 0, 20, 20, 20, 0, 20, 20, 0, 20],
        ["69121", 20, 20, 40, 0, 0, 0, 20, 20, 40, 20, 0, 20, 20, 0, 20],
        ["69124", 20, 20, 40, 0, 0, 0, 0, 0, 0, 20, 0, 20, 0, 0, 0],
        ["69221", 20, 20, 40, 20, 0, 20, 0, 0, 0, 20, 0, 20, 20, 20, 40]
      ]
    }
  };

  $scope.cellColor = "blue";

  $scope.updateCellColor = function(col){
    if(parseInt(col)===parseInt(0)){
        alert('changing color to red');
        $scope.cellColor = "red";
    }else{
        alert('changing color to yellow');
        $scope.cellColor = "yellow";
    }
  };

});

CSS

.red{
    color:red;
}

.blue{
    color:blue;
}

.yellow{
    color:yellow;
}

The problem is that you are binding all the cells to the value of the scope's cellColor variable. If you want to do what you are trying to do, then one solution would be to create a directive that you apply to each cell that has its own cellColor variable that overrides the one inherited from the parent scope when the callback is called.

Here is another solution with directives which handles the DOM directly.

HTML

<body ng-app="app">
  <div ng-controller="MainCtrl">
    <table>
      <tbody>
        <tr ng-repeat="row in tableType.data.rows track by $index">
          <td ng-repeat="col in row track by $index" >
            <span id={{col}} highlight-on-click>{{col}}</span>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</body>

Directive

app.directive('highlightOnClick', function(){
  return {
    restrict: 'A',
    link: function($scope, element){
      element.bind('click', function(){
         if(parseInt(element.text()) === 0){
           element.toggleClass('red');
         } else {
           element.toggleClass('yellow');
         }   
      })
    }
  }

Working sample here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM